Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resizing d3 / dagre-d3 svg to show all contents

I'm trying to create DAGs with dagre-d3. The data for these DAGs comes from a database, are different for each DAG and as such, I do not know the width/height to give the containing svg before adding all nodes and edges to the graph.

So ideally I'd call something like d3.select("#svg1").resize_to_match_contents() after adding all nodes and edges to make sure all nodes are visible and the svg isn't too large. Of course there is no such function, and I have no idea how to implement it. I know I can call d3.select("#svg1").attr("height", "10") to set the height, but have no idea how to retreive/compute what the height of the <g> element inside the SVG is.

like image 490
Dennis Kaarsemaker Avatar asked Nov 17 '13 10:11

Dennis Kaarsemaker


1 Answers

The internal and external dimensions of SVG can be independently controlled using the viewBox attribute. When you talk about finding the size of the g element, it only makes sense if there there is no viewBox defined and there are no other scale transformations anywhere.

svg width height and viewBox

Here is how I would suggest you do it:

  1. Set the width/height of the svg element to the window.innerWidth and window.innerHeight, or to the maximum dimension you want it to grow to.
  2. Set the viewBox attribute to something like "0 0 100 100" and then define all scales in your code to have the domain [0, 100]. This will ensure that the graph shrinks to fit in your designated area.

Also, take a look at how nvd3 handles window resizes, and how to maintain the coordinate system inside the SVG element upon resize using preserveAspectRatio.


From what I could glean from their webpage, darge-d3 does not allow for setting the layout options to limit the render size explicitly and does not return the maximum dimensions it used. One could, however, use getBBox() to get the dimensions of the g box where it rendered and try to set the viewBox such that it just fits the SVG (or set the height, width on the SVG to match the dimension for the g 1:1, but that could lead to a broken layout.

like image 84
musically_ut Avatar answered Sep 22 '22 07:09

musically_ut