开发者

Get svg graphics size when width/height attributes on <svg> are not set

开发者 https://www.devze.com 2022-12-15 05:15 出处:网络
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 get

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:

  1. 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;

  2. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消