相对较新的D3,有一个关于线的翻译(动画)的问题。我使用以下代码为圈子设置动画:
var data = d3.range(100).map(function() {
return new agent(
0,
0,
(Math.random()-0.5)*.05,
(Math.random()-0.5)*.05,
'rgb(255, 0, 213)');
});
var circles = canvas.selectAll('circle')
.data(data)
.enter().append('circle')
.attr('cx', function(d) {
return d.x;
})
.attr('cy', function(d) {
return d.y;
})
.attr('r', 5)
.attr('fill', function(d) {
return d.color;
});
circles.attr('transform', function(d) {
return 'translate(' + d.x + ',' + d.y + ')';
});
我最感兴趣的是最后3行 - 对于行是否有等效的translate
?
答案 0 :(得分:2)
有几种可能的选项可以在D3中为线条设置动画,例如
更改基础数据
svg.select(".line")
.duration(animationLength)
.attr("d", valueline(lineData))
valueLine是d3.svg.line()
函数。
var lineGraph = svg.append("path")
.attr("class", "line")
.attr("d", lineFunction(lineData))
.attr("stroke-dasharray", 200 + " " + 200)
.attr("stroke-dashoffset", 200)
.attr("fill", "none")
.transition()
.duration(animationLength)
.ease("linear")
.attr("stroke-dashoffset", 0);
使用transform
移动线
svg.select(".line")
.duration(animationLength)
.attr("transform", "translate(" + 100 * Math.random() + "," + 100 * Math.random() + ")");
var animationLength = 2000;
var lineData = [{
"x": 1,
"y": 5
}, {
"x": 20,
"y": 20
}, {
"x": 40,
"y": 10
}, {
"x": 60,
"y": 40
}, {
"x": 80,
"y": 5
}, {
"x": 100,
"y": 60
}];
var lineFunction = d3.svg.line()
.x(function (d) {
return d.x;
})
.y(function (d) {
return d.y;
})
.interpolate("linear");
var valueline = d3.svg.line()
.x(function (d) {
return d.x * (Math.random() + 0.5);
})
.y(function (d) {
return d.y * (Math.random() + 0.5);
});
var svg = d3.select("#line")
.append("svg")
.attr("width", 200)
.attr("height", 200);
var lineGraph = svg.append("path")
.attr("class", "line")
.attr("d", lineFunction(lineData))
.attr("stroke", "blue")
.attr("stroke-width", 2)
.attr("stroke-dasharray", 200 + " " + 200)
.attr("stroke-dashoffset", 200)
.attr("fill", "none")
.transition()
.duration(animationLength)
.ease("linear")
.attr("stroke-dashoffset", 0);
svg = d3.select("body").transition();
svg.select(".line")
.delay(animationLength)
.duration(animationLength)
.attr("d", valueline(lineData))
.attr("transform", "translate(" + 100 * Math.random() + "," + 100 * Math.random() + ")");

<script src="https://d3js.org/d3.v3.min.js"></script>
<div id="line"></div>
&#13;