2017-02-15 94 views
1

我想在窗口大小調整時更新氣泡圖的模擬。到目前爲止,氣泡的半徑調整了大小,但cx座標不更新,並且氣泡保持在第一次渲染的位置。在d3.vs4上調整D3 ForceSimulation

var simulation=d3.forceSimulation() 
      .force('x',d3.forceX(function(d){return xScale(d.n);})) 
      .force('y',d3.forceY(height)) 
      .force('collide',d3.forceCollide(function(d){return rScale(d.m);})); 
simulation.nodes(data) 
    .on('tick',ticked); 
function ticked(){ 
    dot 
     .attr('cx',function(d){return d.x;}) 
     .attr('cy',function(d){return d.y;}) 
} 

d3.select(window).on('resize',resize); 
function resize(){ 
    //get width of window 
    //update xScale and rScale 
    //update radius of bubbles 
    simulation 
     .force('x',d3.forceX(function(d){return xScale(d.n);})) 
     .force('y',d3.forceY(height)) 
     .force('collide',d3.forceCollide(function(d){return rScale(d.m);})); 
    simulation.nodes(data) 
     .on('tick',ticked); 
    function ticked(){ 
     dot 
      .attr('cx',function(d){return d.x;}) 
      .attr('cy',function(d){return d.y;}) 
    } 
} 

回答

1

您將需要使用.restart()方法重新啓動您的力仿真,並使用.alpha()或.alphaTarget()值進行遊玩。你的代碼有一些不必要的重複。

也許類似下面的內容可能適合您的使用情況?

var simulation=d3.forceSimulation() 
 
      .force('x',d3.forceX(function(d){return xScale(d.n);})) 
 
      .force('y',d3.forceY(height)) 
 
      .force('collide',d3.forceCollide(function(d){return rScale(d.m);})); 
 
simulation.nodes(data) 
 
    .on('tick',ticked); 
 
    
 
function ticked(){ 
 
    dot 
 
     .attr('cx',function(d){return d.x;}) 
 
     .attr('cy',function(d){return d.y;}) 
 
} 
 

 
d3.select(window).on('resize',resize); 
 
function resize(){ 
 
    //get width of window 
 
    //update xScale and rScale 
 
    //update radius of bubbles 
 
    simulation 
 
     .force('x',d3.forceX(function(d){return xScale(d.n);})) 
 
     .force('collide',d3.forceCollide(function(d){return rScale(d.m);})) 
 
     // 0.3 is arbitrary 
 
     .alpha(0.3) 
 
     .restart() 
 

 
}