Reputation: 31
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?
Upvotes: 3
Views: 2864
Reputation: 1706
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.
Upvotes: 4
Reputation: 109232
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)); });
}
Upvotes: 3