我在D3中使用了一种面向对象的方法(参见Org
类)写了一点Javascript。我希望圆圈在随机(x,y)位置之间平滑地动画,但是我写的代码被卡住而没有渲染任何东西(白色页面,微调框)。如果我排除while(true)
,圆圈渲染效果非常好,但我需要它们进行动画制作 - 请帮助!D3 Javascript循环无法渲染
我的第二个问题是以这种面向对象的方式使用D3是否有意义?在像Java这样的类OOP语言中,我会做类似orgs[x].width++
的操作,并调用某种重新渲染函数,但是D3会执行那些对内存保留的引用,或者每次更改时都必须更新圆圈数据(即circles.data(orgs)
)?
class Org {
constructor(_width, _height) {
this.width = _width;
this.height = _height;
}
}
var canvas = d3.select('body')
.append('svg')
.attr('width', screen.width)
.attr('height', screen.height);
var orgs = d3.range(100).map(function() {
return new Org(Math.random() * screen.width, Math.random() * screen.height);
});
var circles = canvas.selectAll("circle")
.data(orgs)
.enter().append('circle')
.attr('cx', d => d.width)
.attr('cy', d => d.height)
.attr('r', 5)
.attr('fill', 'rgb(255, 0, 213)');
while (true) { //Sticks without rendering
this.update();
}
function update() {
circles.transition()
.attr('cx', function() { return Math.random() * screen.width; })
.attr('cy', function() { return Math.random() * screen.height; });
}