javascript - D3 中的循环过渡

标签 javascript svg d3.js

基本说明:我有点像 D3 新手。

我的目标是让一条线从 A 点移动到 B 点,然后立即重新出现在 A 点并重复该过渡。我尝试了很多不同的方法,但这是我最接近的方法。

var svg = d3.select("body")
        .append("svg")
        .attr("width", 500)
        .attr("height", 500);

// code, code, code, irrelevant code...

function timeForTimeline(){ // har
    var timeline = svg.append("line")
        .attr("stroke", "steelblue")
        .attr({
            'x1': 0,
            'y1': 130,
            'x2': 168,
            'y2': 130
        });
    (function repeat() {
        timeline = timeline
            .transition()
            .duration(4000)
            .ease("linear")
            .attr({
                'x1': 0,
                'y1': 430,
                'x2': 168,
                'y2': 430   
            })
            .each("end", function(){
                d3.select(this)
                    .transition()
                    .duration(0)
                    .attr({
                        'x1': 0,
                        'y1': 130,
                        'x2': 168,
                        'y2': 130
                    })
                    .each("end", repeat);
            });
    })();
};

结果是一个很好的开始过渡,随后在没有 duration(4000) 位生效的情况下,行在 A 点和 B 点之间快速跳转。我还尝试删除底部的行 (d3.select(this).remove()),然后在每次调用 repeat() 的顶部附加一个新行。我也试过只重置 x1、x2、y1 和 y2 并完全跳过过渡。我并不是说我尝试了这些方法是正确的,但我的结果要么根本没有线,要么是无限线,要么是一条线到达 B 点并停留在那里。

关于如何实现我的(可能非常简单的)目标还有其他建议吗?非常感谢您的帮助!

最佳答案

在我看来,您不需要两次指定起始坐标。您可以在 repeat 函数中分配初始坐标,然后像这样立即调用它:

function timeForTimeline() {
    var timeline = svg.append("line")
        .attr("stroke", "steelblue");

    repeat();

    function repeat() {
      timeline.attr({
        'x1': 0,
        'y1': 130,
        'x2': 168,
        'y2': 130
      })
      .transition()
      .duration(4000)
      .ease("linear")
      .attr({
        'x1': 0,
        'y1': 430,
        'x2': 168,
        'y2': 430   
      })
      .each("end", repeat);
    }
}

这是一个 fiddle

关于javascript - D3 中的循环过渡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23232929/

相关文章:

javascript - 下载文件时防止用户交互的正确方法是什么?

html - 如何使用文本元素从下到上在 SVG1.1 中显示文本?

javascript - 如何在 d3.js 中适应我的 svg 矩形框中的文本?

javascript - 如何修复 CORS 错误以提供虚假开发数据

javascript - Mysql to JSON to D3js no Visual... "class"识别错误

javascript - c3.js 鼠标悬停时不显示值

javascript - 无阻塞地下载javascript

javascript - 如何正确访问像这样的javascript "dictionary"

javascript - Safari 中是否可以使用 Http Streaming Comet?

R&Inkscape : text labels in SVG graphics exported from R did not recognized as a text in Inkscape