gpt4 book ai didi

javascript - Stroke-dashoffset 和 dasharray 动画不起作用

转载 作者:行者123 更新时间:2023-11-28 17:32:49 26 4
gpt4 key购买 nike

我正在尝试在 D3 中制作路径线动画。我可以让其他过渡起作用,例如淡入淡出效果,但在研究如何过渡路径之后,似乎最好的选择是通过修改它来使用笔画 dasharray

var data = {
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"properties": {
"name": "Test Drive for data ",
"time": "2018-04-03T01:48:51Z",
"coordTimes": []
},
"geometry": {
"type": "LineString",
"coordinates": [
[10, 10, 10],
[30, 40, 10],
[50, 20, 10],
[70, 100, 10],
[90, 20, 10],
[110, 120, 10],
[130, 100, 10],
[150, 80, 10]
]
}
}]
}

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

var lineFunction = d3.line()
.x(function(d) {
return d[0]
})
.y(function(d) {
return d[1]
})
.curve(d3.curveBasis);

var totalLength = d3.line(data).length;

var tripLine = svg.append("path")
.datum(data.features[0].geometry.coordinates)
.attr("id", "pathLine")
.style("stroke-dasharray", 0)
.attr("d", lineFunction)
.style("stroke", "#ddd")
.transition()
.duration(2000)
.style("stroke", "red")
.style("stroke-dasharray", totalLength + " " + totalLength)
.attr("stroke-width", 4)
.attr("fill", "none");
<script src="https://d3js.org/d3.v5.min.js"></script>

问题在于,D3 使使用之前的示例变得极其困难,因为对语法进行了更新,使得无法获取路径的总长度。

最佳答案

这里有一个基本错误:d3.line(data).length,顺便说一下,它与 d3.line().length 相同,将返回1。

您想要的方法是getTotalLength ,必须在 SVG 元素 上调用,而不是在 D3 选择上调用,甚至更少在线条生成器上调用。

因此:

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

这是更新后的代码:

var data = {
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"properties": {
"name": "Test Drive for data ",
"time": "2018-04-03T01:48:51Z",
"coordTimes": []
},
"geometry": {
"type": "LineString",
"coordinates": [
[10, 10, 10],
[30, 40, 10],
[50, 20, 10],
[70, 100, 10],
[90, 20, 10],
[110, 120, 10],
[130, 100, 10],
[150, 80, 10]
]
}
}]
}

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

var lineFunction = d3.line()
.x(function(d) {
return d[0]
})
.y(function(d) {
return d[1]
})
.curve(d3.curveBasis);

var tripLine = svg.append("path")
.datum(data.features[0].geometry.coordinates)
.attr("id", "pathLine")
.style("stroke-dasharray", 0)
.attr("d", lineFunction)
.style("stroke", "#ddd")
.attr("fill", "none");

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

tripLine.transition()
.duration(2000)
.style("stroke", "red")
.style("stroke-dasharray", totalLength + " " + totalLength)
.attr("stroke-width", 4);
<script src="https://d3js.org/d3.v5.min.js"></script>

关于javascript - Stroke-dashoffset 和 dasharray 动画不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49893977/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com