Adjust the size of the SVG element for its contents

I would like to customize the dimensions of the SVG-Element to its content.

JSfiddle: http://jsfiddle.net/4pD9N/

Here I gave an example. SVG must be “compressed” to fit elements with a margin of + 10px on each side. In other words: I want to trim svg for unused space ...

I know what I need to use getBBox. But how can I calculate the total width and height?

+4
source share
2 answers

SVG- . , (0,0) SVG. , . viewBox ( : "minx miny width height") SVG getBBox(). http://jsfiddle.net/3cp3c/.

svg.setAttribute("viewBox", (bbox.x-10)+" "+(bbox.y-10)+" "+(bbox.width+20)+" "+(bbox.height+20));
svg.setAttribute("width", (bbox.width+20)  + "px");
svg.setAttribute("height",(bbox.height+20) + "px");
+7
var svg = document.getElementsByTagName("svg")[0];
var bb=svg.getBBox();
var bbx=bb.x;
var bby=bb.y;
var bbw=bb.width;
var bbh=bb.height;
var vb=[bbx,bby,bbw,bbh];
svg.setAttribute("viewBox", vb.join(" ") );
+6

All Articles