我在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; });
}