Skip to content Skip to sidebar Skip to footer

How To Make A Svg Container Hug Its Contents?

I am working on a project where some SVG tags are auto-generated based on the user provided input. For instance the most common scenario I have is that I may have many SVG objects

Solution 1:

Ok, if i understood it well, then you want your 'svg tag' of exact 'height' and 'width' in which its 'child' resides.

one possible solution would be:-

(assuming your svg is positioned at 0,0)

  1. you need to track which element is drawn in your svg (i hope you are already doing this).
  2. then you need to use 'getBbox()' to get its 'height' and 'width'
  3. Now here you need to calculate the exact position of your 'child' element with respect to position (0,0).

lets take an example

var svgwidth=500;
var svgheight=500;

<svgid="svg1"width="500"height="500"></svg>

now let say user draw a rectangle in it.

<rect id="rect1" x="0" y="0" height="200" width="300"></rect>

now we need to determine exact 'width' and 'height' for our 'svg'.

var rect1=document.getElementById('rect1');
var bbox=rect1.getBBox();

var widtharea=bbox.x+bbox.width;
var heightarea=bbox.y+bbox.height;

Now compare 'widtharea' with 'svgwidth', if its larger then 'svgwidth', update value of 'svgwidth'. similarly compare 'heightarea' with 'svgheight'

you need to perform above step every time user create any element in svg.

Post a Comment for "How To Make A Svg Container Hug Its Contents?"