最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Resizing D3 force layout - Stack Overflow

programmeradmin1浏览0评论

Is it possible to resize a force layout in 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?

Is it possible to resize a force layout in 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?

Share edited Feb 4, 2014 at 22:34 VividD 10.5k8 gold badges66 silver badges112 bronze badges asked Oct 10, 2013 at 17:59 jcmittjcmitt 311 silver badge2 bronze badges 9
  • 1 Have you tried resetting .size()? – Lars Kotthoff Commented Oct 10, 2013 at 18:12
  • I tried force.size([newWidth, height]).start(); to no avail... – jcmitt Commented Oct 10, 2013 at 18:35
  • Note that increasing the size of the layout doesn't mean that the additional space will be used. What is your specific use case for this? – Lars Kotthoff Commented Oct 10, 2013 at 18:38
  • I have a few items on one page, and when focused on one of the other layouts, I'd like the force layout to shrink. – jcmitt Commented Oct 10, 2013 at 18:41
  • You'll also have to resize the container. – Lars Kotthoff Commented Oct 10, 2013 at 18:46
 |  Show 4 more ments

2 Answers 2

Reset to default 4

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:

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.

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. You will have to enforce any constraints on that yourself, e.g. in the tick function:

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)); });
}
发布评论

评论列表(0)

  1. 暂无评论