Javascript 未设置 <svg> 上的宽度/高度属性时获取 svg 图形大小
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1976877/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get svg graphics size when width/height attributes on <svg> are not set
提问by Spadar Shut
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.
那么当 svg 元素上没有设置宽度和高度时,如何使用 javascript 获取 SVG 文件的大小?svg 是一个字符串,但如有必要,可以将其设为 DOM。
回答by KeatsKelleher
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.
您可以使用 SVGElement 对象的 getBBox() 方法。它告诉您宽度和高度、x 和 y 偏移(以像素为单位),而不考虑元素的缩放比例。
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 transformationsdone with scale etc.
我最近还了解到,鲜为人知的
getBoundingClientRect()工作也很好!你也可以这样做:var el = document.getElementById('myelem'); var mywidth = el.getBoundingClientRect().width;请记住,getBBox 和 getBoundingClientRect 之间存在差异。getBBox 获取初始尺寸 - getBoundingClientRect 也尊重使用缩放等完成的转换。
回答by jball
SVGs are scalablevector graphics, and thus can have any arbitrary height and width. Only the ratio is fixed by the format.
SVG 是可缩放的矢量图形,因此可以具有任意的高度和宽度。只有比率由格式固定。

