在d3中链接转换的正确方法是什么?

时间:2014-10-11 21:59:49

标签: javascript d3.js transitions

受此other question的启发,我创建了一个绘制圆圈的动画(jsfiddle),然后创建了一条将其连接到另一个圆圈的线条。我读到D3 v3不需要监听end事件到链转换。

enter image description here

下面的代码有效,但我应该如何重构它以便它不会使用end个事件?

var margin = {top: 40, bottom: 40, left: 40, right: 40},
    width = 960 - margin.left - margin.right,
    height = 500 - margin.bottom - margin.top;

var svg = d3.select("body").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var t0 = svg.append("circle")
    .attr("r", 0)
    .attr("cx", 40)
    .attr("cy", 40)
    .attr("class", "point")
  .transition()
    .duration(500)
    .attr("r", 4);

var t1 = t0.each("end", function(){ 
    var t2 = svg.append("path")
        .style("stroke", "#000")
        .style("stroke-width", 2)
        .style("fill", "none")
        .attr("d", "M40,40L40,40")
      .transition()
        .ease("linear")
        .duration(500)
        .attr("d", "M40,40L80,80");

    t2.each("end", function(){ 
        svg.append("circle")
            .attr("r", 1)
            .attr("cx", 80)
            .attr("cy", 80)
            .attr("class", "point")
          .transition()
            .duration(500)
            .attr("r", 4);
    });
});

1 个答案:

答案 0 :(得分:1)

好的,感谢评论,我意识到我可以这样做:

  • 附加第一个项目并使用t0 = svg.transition()
  • 创建第一个转换
  • 附加第二项并创建第二个转换(将在t0结束后触发)t1 = t0.transition()
  • 重复第三项t2 = t1.transition()

请注意,如果要更改每个转换的持续时间,则必须在定义转换时完成。这是错的:

var t1 = t0.transition()
    .ease("linear");
t1.select("path.line")
    .duration(500)
    .attr("d", "M40,40L80,80");

应该是:

var t1 = t0.transition()
    .ease("linear");
    .duration(500)
t1.select("path.line")
    .attr("d", "M40,40L80,80");

这是最终代码(jsfiddle):

var margin = {top: 40, bottom: 40, left: 40, right: 40},
    width = 960 - margin.left - margin.right,
    height = 500 - margin.bottom - margin.top;

var svg = d3.select("body").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

svg.append("circle")
    .attr("r", 0)
    .attr("cx", 40)
    .attr("cy", 40)
    .attr("class", "point-start")

svg.append("path")
    .style("stroke", "#000")
    .style("stroke-width", 2)
    .style("fill", "none")
    .attr("class", "line")
    .attr("d", "M40,40L40,40");

svg.append("circle")
    .attr("r", 0)
    .attr("cx", 80)
    .attr("cy", 80)
    .attr("class", "point-end")

var t0 = svg.transition()
    .duration(100);

t0.select("circle.point-start")
    .attr("r", 4);

var t1 = t0.transition()
    .duration(500)
    .ease("linear");
t1.select("path.line")
    .attr("d", "M40,40L80,80");

var t2 = t1.transition()
    .duration(100);
t2.select("circle.point-end")
    .attr("r", 4);