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?
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.
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.
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 .
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");
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(" ") );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With