Reputation: 15817
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.
Upvotes: 17
Views: 21449
Reputation: 10191
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.
Upvotes: 39
Reputation: 25024
SVGs are scalable vector graphics, and thus can have any arbitrary height and width. Only the ratio is fixed by the format.
Upvotes: -3