简体   繁体   English

调整D3力布局的大小

[英]Resizing D3 force layout

Is it possible to resize a force layout in d3.js? 是否可以在d3.js中调整力布局的大小? For example, I have a layout defined by 例如,我有一个定义的布局

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

force.start();

and I wish to resize it later in the project. 我希望稍后在项目中重新调整大小。 Is this possible? 这可能吗?

Shortly, on a resize event you should change the attributes of your svg object (it changes also the center of gravity) and resume force calculations: 不久,在调整大小事件时,您应该更改svg对象的属性(它也会改变重心)并恢复力计算:

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

An example for the d3 force resize is provided here . 这里提供d3强制调整大小的示例。

According to the documentation , the .size() parameter of the force layout affects only the center of gravity and initial distribution of nodes, not the space available. 根据文档 ,力布局的.size()参数仅影响重心和节点的初始分布,而不影响可用空间。 You will have to enforce any constraints on that yourself, eg in the tick function: 您必须自己强制执行任何约束,例如在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)); });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM