Get svg graphics size when width/height attributes on <svg> are not set
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.
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.
SVGs are scalable vector graphics, and thus can have any arbitrary height and width. Only the ratio is fixed by the format.
精彩评论