我正在尝试在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使用先前的示例非常困难,因为对语法的更新使得无法获得路径的总长度。
答案 0 :(得分:3)
此处存在一个基本错误: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);
&#13;
<script src="https://d3js.org/d3.v5.min.js"></script>
&#13;