【问题标题】:D3 Javascript loop doesn't renderD3 Javascript循环不呈现
【发布时间】:2016-11-23 01:34:24
【问题描述】:

我使用面向对象的方法在 D3 中快速编写了一点 Javascript(请参阅 Org 类)。我想让圆圈在随机(x,y)位置之间平滑动画,但是我编写的代码在没有渲染任何东西(白页,微调器)的情况下卡住了。如果我排除 while(true),圆圈渲染得非常漂亮,但我需要它们来制作动画 - 请帮助!

我的第二个问题是以这种面向对象的方式使用 D3 有意义吗?在像 Java 这样的类 OOP 语言中,我会做类似orgs[x].width++ 的事情并调用某种重新渲染函数,但是使用 D3 会保留对内存的引用,或者我是否必须在每次更改时更新圆数据(即@987654324 @)?

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

【问题讨论】:

    标签: javascript html oop d3.js


    【解决方案1】:

    没有breakwhile(true) 将永远循环(无限循环),因为true 始终为真。你可以这样做:

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

    update 只运行一次。

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

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

    所以,每个函数都取消了前一个函数,没有任何反应。如果您想要重复的update,请使用不同的方法,例如递归或setInterval,但不是这个while(true)

    (关于你的第二个问题,对于 S.O. 来说似乎“过于宽泛”,因此,我不会发表我的意见,但我认为这在 D3 社区中并不常见)

    【讨论】:

      猜你喜欢
      • 2014-08-21
      • 2017-01-02
      • 2016-08-29
      • 2022-01-06
      • 1970-01-01
      • 1970-01-01
      • 2018-03-26
      • 2019-03-10
      • 1970-01-01
      相关资源
      最近更新 更多