我已经成功地实现了来自 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);
})
提前致谢
最佳答案
有趣的副作用。 无论如何,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 .
据我所知:
- 将路径虚线模式初始化为 totallength 可见,totallength 不可见
- 先设置dashoffset为totallength,只让gap部分可见
- 过渡到 dashoffset 为 0,使只有破折号部分可见。
- 点击时,再次过渡到 totallength dash offset,再次使间隙部分可见。
为了好玩,更改 dasharray 的设置:.attr("stroke-dasharray", totalLength/2 + ""+ totalLength/2)
关于javascript - 需要D3动画画线的说明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18847266/