我正在尝试在窗口调整大小时更新气泡图的模拟。到目前为止,气泡的半径调整大小但cx坐标不会更新,气泡会保留在首次渲染的位置。
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;})
}
}
答案 0 :(得分:2)
您将需要使用.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()
}