Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adjust size of an SVG-element to its content

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

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

Here I got an example. The SVG should 'shrink' to fit to the elements + 10px margin on each side. In other words: I want to crop the svg for the unused space...

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

like image 426
user3142695 Avatar asked Jul 17 '14 11:07

user3142695


People also ask

Can you set the size of an SVG?

Any height or width you set for the SVG with CSS will override the height and width attributes on the <svg> . So a rule like svg {width: 100%; height: auto;} will cancel out the dimensions and aspect ratio you set in the code, and give you the default height for inline SVG.

How do I scale SVG viewBox?

We use viewBox to make the SVG image scalable. viewBox = “0 0 100 100”: defines a coordinate system having x=0, y=0, width=100 units and height=100 units. Thus, the SVG containing a rectangle having width=50px and height=50px will fill up the height and width of the SVG image, and all the dimensions get scaled equally.

How do I change the size of an SVG react?

You can change the size using CSS transform: scale(2) in <ComponentName /> , which in React can be achieved using className or a global CSS file. Note: To change the color you can use . componentClass path { fill: "color" } , but if you change the scale on .


2 Answers

By default, the origin of the SVG drawing is the same as the origin of the container. It means that the (0,0) of your drawing is in the upper left corner of the SVG element. To center the content, you should translate the drawing relatively to the container. It can be achieved by modifying the viewBox attribute (four values expected : "minx miny width height") of the SVG element with respect to the result of the getBBox() method. A live example at 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");
like image 155
user3786597 Avatar answered Oct 24 '22 22:10

user3786597


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(" ") );
like image 34
user3848987 Avatar answered Oct 24 '22 21:10

user3848987