2016-11-23 44 views
0

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

回答

0

一个while(true)没有break将永远循环(无限循环),因为true始终是真实的。你可以这样做:

while (true) { 
    this.update(); 
    break; 
} 

使update只运行一次。

除此之外,请记住,如果您未指定转换的duration(),D3会将默认持续时间设置为250毫秒。从API:

如果未指定持续时间,则默认为250ms的

因此,每个功能取消的先例之一,并没有任何反应。如果您想要重复使用update,请使用不同的方法,如递归或setInterval,但不要使用此while(true)

(关于你的第二个问题,S.O.似乎“太宽泛了”,因此,我不会发表我的意见,但我认为它不是D3社区中的常见方法)