Resizing d3 / dagre-d3 svg to show all contents
Asked Answered
P

1

11

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.

Parsonage answered 17/11, 2013 at 10:37 Comment(0)
F
8

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.

Flection answered 17/11, 2013 at 11:17 Comment(4)
Thanks, getBBox() was the key. This works: var bbox = d3.select("#svg{{ loop.index }}").node().getBBox(); d3.select("#svg{{ loop.index }}").attr("height", bbox.height + 40).attr('width', bbox.width + 40);Parsonage
Just a heads up - dagre-d3 now exposes width and height attributes on the layout graph. For an example, take a look at: github.com/cpettitt/dagre-d3/blob/master/demo/….Tuberosity
In a nutshell, is the answer just "use the viewbox property of svg to resize the dagre output to fit"? nowadays dagre exposes the output dimensions so getbbox is probably not necessary anymore.Gertudegerty
Does anyone know of a Fiddle/Plunk showing auto-zoom?Incident

© 2022 - 2024 — McMap. All rights reserved.