Bounding box in D3.js

David picture David · Nov 21, 2012 · Viewed 9k times · Source

I think a many of you, who worked with D3.js, already experienced the same thing: your network or whatever moveable elements you took keep flying out of the svg-element if they are pushed to hard. If my network is to large the outer nodes disappear, they kind of 'fall of the edge of the world'.

I'm pretty shure there is a way to make the border of the svg a solid 'wall', so elements can't leave it and fly invisible through space :)

What did you do with this problem? How did you solve it?

Thanks in advance, David

Answer

David picture David · Jan 23, 2013

In the end, if you find the right sites on the web it's pretty easy. http://bl.ocks.org/1129492 does exactly what I wanted - the objects can't slip out of the svg. So he just added some constraints when updating the nodes positions. My 'tick' function ended up like

node.attr("cx", function(d) { return d.x = Math.max(15, Math.min(width - 15, d.x)); })
    .attr("cy", function(d) { return d.y = Math.max(15, Math.min(height - 15, d.y)); });

link.attr("x1", function(d) { return d.source.x; })
    .attr("y1", function(d) { return d.source.y; })
    .attr("x2", function(d) { return d.target.x; })
    .attr("y2", function(d) { return d.target.y; });

node.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });

This is called whenever something important might happen, the "tick"-thing is something built somewhere deep inside D3.js, so don't ask me about that. :)

The first two lines and the last one in the given code check that the coordinates don't get out of the box.

Hope this can help someone out there to do the job faster than I did ;)

Have a good time, Dave