d3 - 慢慢绘制svg路径,行尾消失

时间:2014-05-06 19:34:19

标签: javascript svg d3.js

所以我试图使用d3平滑地绘制五条不同的曲线。 JSFiddle here

为了我的缘故,前4个是硬编码的,第五个是在for循环中推送到lineData数组,因为我最终想要更动态。

var lineData = [[{ "x": 1, "y": 300}, { "x": 200,  "y":70}, { "x": 450,  "y": 300}],
                  [{ "x": 1, "y": 300}, { "x": 250,  "y":70}, { "x": 550,  "y": 300}],
                  [{ "x": 1, "y": 300}, { "x": 300,  "y":70}, { "x": 620,  "y": 300}],
                  [{ "x": 1, "y": 300}, { "x": 350,  "y":70}, { "x": 720,  "y": 300}]];

for (var i = 0; i < 1; i++) {
    lineData.push([{ "x": 1, "y": 300}, { "x": 280,  "y":70}, { "x": 580,  "y": 300}]);
  };

我正在使用使用here的笔画偏移技术,将短划线数组加倍,将偏移设置为每条路径的长度,然后慢慢使偏移返回到0.

但是,这会导致我的最后一条曲线缩短,我无法弄清楚原因。

 $(".line").each(function(i,d){

    var t = [1100, 1304,4506,8101,10607, 12900],
    bases = ["first", "second", "third", "fourth"];

    var totalLength = d.getTotalLength();

      d.style.transition = d.style.WebkitTransition = 'none';

      d3.selectAll("path").attr("stroke-dasharray", totalLength + " " + totalLength)
      .attr("stroke-dashoffset", totalLength)
      .transition()
      .duration(function(d,i) { return t[i]; })
      .ease("linear")
      .attr("stroke-dashoffset", 0)
      .each("end", function() { 
        svg.append("text")
        .attr("class", "t")
        .attr("x", w / 2)
        .attr("y", h)
        .attr("text-anchor", "middle");

     });

我已经玩过了我给破折号数组和动画时间的长度,但我似乎无法找到造成这种奇怪行为的原因。

我也对第五行进行了硬编码,并且运行良好,所以问题可能在于我添加了这些行?

这是jsfiddle我的问题:非常感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

问题是在遍历所有行的循环内部,您再次选择所有路径(d3.selectAll("path"))。也就是说,对于每一行,您选择所有其他行并根据您在外部循环中选择的行的长度设置动画。线条长度不同,因此有些线条不足。

要修复,只需选择内循环中的当前行而不是所有行:

d3.select(this).attr("stroke-dasharray", totalLength + " " + totalLength)
// ...

完整演示here。还有一些其他的东西(例如附加标签),当你只需要一次时,你为每一行运行,但我没有修复它们。