我使用面向对象的方法(参见Org类)用D3编写了一小段Javascript。我想让圆在随机(x,y)位置之间平滑地动画,但是我写的代码在没有渲染任何东西(白页,微调器)的情况下被卡住了。如果我排除了while(true),圆圈渲染得很漂亮,但我需要它们的动画效果-请帮助!
我的第二个问题是,以这种面向对象的方式使用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; });
}发布于 2016-11-23 12:36:28
没有break的while(true)将永远循环(无限循环),因为true始终为真。您可以执行以下操作:
while (true) {
this.update();
break;
}让update只运行一次。
除此之外,请记住,如果您不指定转换的duration(),D3会将默认持续时间设置为250ms。在API中:
如果未指定持续时间,则默认为250ms
因此,每个函数都会取消前一个函数,并且什么都不会发生。如果需要重复update,请使用不同的方法,如递归或setInterval,但不要使用此while(true)。
(关于你的第二个问题,对于S.O.来说,它似乎“太宽泛”了,因此,我不会给出我的意见,但我认为这不是D3社区中的常见方法)
https://stackoverflow.com/questions/40754640
复制相似问题