2016-11-23 126 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社區中的常見方法)