我绘制一个圆圈并希望运行它从数据集的第一个点到最后一个点的转换。但无法理解如何做到这一点。可用代码here。我该怎么做?这种动画的最佳实践是什么?
var data = [[{
x: 10,
y: 10,
r: 10,
color: "red"
}, {
x: 70,
y: 70,
r: 15,
color: "green"
}, {
x: 130,
y: 130,
r: 20,
color: "blue"
}]];
function setUp() {
this.attr("cx", function(d, i) {
return d[i].x;
}).attr("cy", function(d, i) {
return d[i].y;
}).attr("r", function(d, i) {
return d[i].r;
}).attr("fill", function(d, i) {
return d[i].color;
});
}
var canvas = d3.select("body")
.append("svg")
.attr("width", 300)
.attr("height", 300);
canvas.append("rect")
.attr("width", 300)
.attr("height", 300)
.attr("fill", "lightblue");
var circles = canvas.selectAll("circle")
.data(data)
.enter()
.append("circle")
.call(setUp);
答案 0 :(得分:1)
您是否想要something like this?
var data = [[{
x: 10,
y: 10,
r: 10,
color: "red"
}], [{
x: 70,
y: 70,
r: 15,
color: "green"
}], [{
x: 130,
y: 130,
r: 20,
color: "blue"
}]];
...
var circles = canvas.selectAll("circle")
.data(data[0]);
circles
.enter()
.append("circle")
.call(setUp);
circles
.data(data[1])
.transition()
.duration(2000)
.call(setUp)
.each("end",function(){
circles
.data(data[2])
.transition()
.duration(2000)
.call(setUp);
});
修改评论
如果你有一个可变数量的点,这是一个使用递归函数的好地方:
// first point
var circles = canvas.selectAll("circle")
.data([data[0]]);
circles
.enter()
.append("circle")
.call(setUp);
// rest of points...
var pnt = 1;
// kick off recursion
doTransition();
function doTransition(){
circles
.data([data[pnt]])
.transition()
.duration(2000)
.call(setUp)
.each("end",function(){
pnt++;
if (pnt >= data.length){
return;
}
doTransition();
});
}
更新了example。