调整D3力布局的大小

时间:2013-10-10 17:59:43

标签: javascript d3.js resize force-layout

是否可以在d3.js中调整力布局的大小?例如,我有一个由

定义的布局
var force = d3.layout.force()
.nodes(documents.nodes)
.linkDistance(0)
.friction(.2)
.size([width, height]);

force.start();

我希望稍后在项目中调整大小。这可能吗?

2 个答案:

答案 0 :(得分:4)

很快,在调整大小事件时,您应该更改 svg对象的属性(它也会改变重心)并恢复力计算:

window.onresize = function() {
  width = window.innerWidth, height = window.innerHeight;
  svg.attr('width', width).attr('height', height);
  force.size([width, height]).resume();
};

d3 force 调整大小的示例是provided here

答案 1 :(得分:3)

根据the documentation,力布局的.size()参数仅影响重心和节点的初始分布,而不影响可用空间。你必须自己强制执行任何限制,例如:在tick函数中:

force.on("tick", function() {
    node.attr("cx", function(d) { return Math.min(maxX, Math.max(minX, d.x)); })
        .attr("cy", function(d) { return Math.min(maxY, Math.max(minY, d.y)); });
}