最好移动它们,因为这是您可以在没有错误的情况下制作动画的唯一方法。
在 d3.js 中,对象是数据绑定的。清除和重新绘制“画布”不是正确的方法。首先,它不是画布,而是网页,任何清除和重绘都由浏览器本身处理。基本上,您的工作是将数据绑定到 SVG。
您需要利用 d3 事件 enter、exit、update,它们处理 SVG 在数据绑定基础数据被修改时的行为,并让 d3 处理动画。
最简单的例子在这里:https://bost.ocks.org/mike/circles/
- 选择您的元素,并将选择存储在一个变量中
var svg= d3.select("svg");
var circles = svg.selectAll('circle');
- 现在我们需要将一些数据绑定到圆。
var databoundCircles = circles.data([12,13,14,15,66]);
这个数据可以是任何东西。通常我会期望一个对象列表,但这些都是简单的数字。
- 处理数据出现时的“制造”方式
databoundCircles.enter().append('circle');;
- 处理删除数据时发生的情况
databoundCircles.exit().remove()
- 处理数据更新时发生的情况
databoundCircles.attr('r', function(d, i) { return d * 2; })
这将在数据更改时更改半径。
回顾该教程:
enter - 传入元素,进入舞台。
更新 - 持久元素,留在舞台上。
exit - 传出元素,退出舞台。
因此总结:不要像你现在那样做。确保您专门使用这些事件来处理元素的生命周期。
专业提示:如果您使用对象列表,请确保通过 id 或某个唯一标识符绑定数据,否则动画可能会随着时间的推移而出现异常行为。请记住,您将数据绑定到 SVG,而不仅仅是擦除和重绘画布!
d3.selectAll('circle').data([{id:1},{id:2}], function(d) { return d.id; });
记下可选的第二个参数,它告诉我们如何绑定数据!非常重要!
var svg = d3.select("svg");
//the data looks like this.
var data = [{
id: 1,
r: 3,
x: 35,
y: 30
}, {
id: 2,
r: 5,
x: 30,
y: 35
}];
//data generator makes the list above
function newList() {
//just make a simple array full of the number 1
var items = new Array(randoNum(1, 10)).fill(1)
//make the pieces of data. ID is important!
return items.map(function(val, i) {
var r = randoNum(1, 16)
return {
id: i,
r: r,
x: randoNum(1, 200) + r,
y: randoNum(1, 100) + r
}
});
}
//im just making rando numbers with this.
function randoNum(from, to) {
return Math.floor(Math.random() * (to - from) + from);
}
function update(data) {
//1. get circles (there are none in the first pass!)
var circles = svg.selectAll('circle');
//2. bind data
var databoundCircles = circles.data(data, function(d) {
return d.id;
});
//3. enter
var enter = databoundCircles.enter()
.append('circle')
.attr('r', 0)
//4. exit
databoundCircles.exit()
.transition()
.attr('r', 0)
.remove();
//5. update
//(everything after transition is tweened)
databoundCircles
.attr('fill', function(d, i){
var h = parseInt(i.toString(16));
return '#' + [h,h,h].join('');
})
.transition()
.duration(1000)
.attr('r', function(d, i) {
return d.r * 4
})
.attr('cx', function(d, i) {
return d.x * 2;
})
.attr('cy', function(d, i){
return d.y * 2
})
;
}
//first time I run, I use my example data above
update(data);
//now i update every few seconds
//watch how d3 'keeps track' of each circle
setInterval(function() {
update(newList());
}, 2000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<svg width="500" height="300">
</svg>