Resizing d3 / dagre-d3 svg to show all contents

China☆狼群 提交于 2019-11-30 09:10:25
musically_ut

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!