需要说明D3动画线条图

时间:2013-09-17 10:22:47

标签: javascript d3.js data-visualization

我已成功实施了this D3 example of animated line drawing的一些代码,但我对它的工作原理并不了解。我真的很感激代码如何工作的逐行细分。我对D3比较新;我理解使用库操作DOM的基础知识,但我觉得这需要我缺乏的中级理解。

我已经在下面列出了我重新设计的示例的特定部分。我怀疑聪明的部分与.attr("stroke-dashoffset", 0);& .attr("stroke-dashoffset", totalLength);部分明确解释了这些工作的方式以及它们对效果的贡献将非常感激。

var totalLength = path.node().getTotalLength();

path
  .attr("stroke-dasharray", totalLength + " " + totalLength)
  .attr("stroke-dashoffset", totalLength)
  .transition()
    .duration(2000)
    .ease("linear")
    .attr("stroke-dashoffset", 0);

svg.on("click", function(){
  path      
    .transition()
    .duration(2000)
    .ease("linear")
    .attr("stroke-dashoffset", totalLength);
})

非常感谢提前

1 个答案:

答案 0 :(得分:2)

有趣的副作用。 无论如何,dasharray和dashoffset SVG属性:https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke-dasharray https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke-dashoffset

据我所知:

  1. 将路径虚线模式初始化为可见总长度,并且总长度不可见
  2. 首先将dashoffset设置为totallength,只显示间隙部分
  3. 转换到dashoffset为0,只显示破折号部分。
  4. 点击后,再次转换为totallength dash offset,再次只显示间隙部分。
  5. 只是为了比赛,更改dasharray的设置:.attr(“stroke-dasharray”,totalLength / 2 +“”+ totalLength / 2)