So how to get the size of an SVG file with javascript when width and height are not set on the svg element? The svg is a string, but could be made a DOM if necessary.
To get width and height of SVG element with JavaScript, we can use the getBoundingClientRect method. const el = document. getElementById("yourElement"); const rect = el.
Add viewBox="0 0 640 480" and set width="320" height="240" to the <svg> element to scale the SVG. you can go crazy on the width and height and control the aspect ratio with the preserveApsectRatio attribute.
SVG's exported from Illustrator CC are 'responsive' by default, in other words there is no height or width attributes, no dimensions. This can be great, but sometimes you may want to force dimensions. Say for example you want to use an SVG for a logo on your website, but you want it to be a set size.
You can use the getBBox() method of the SVGElement object. It tells you the width and height, x, and y offset in pixels without taking into account the scaling of the element.
document.getElementById('myelem').getBBox().width
document.getElementById('myelem').getBBox().height
are what you're looking for, I think.
EDIT:
I've recently also learned that the little known getBoundingClientRect()
works as well! You can also do: var el = document.getElementById('myelem'); var mywidth = el.getBoundingClientRect().width;
Keep in mind that there is a difference between getBBox and getBoundingClientRect. getBBox gets the initial dimensions - getBoundingClientRect also respects the transformations done with scale etc.
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