获取SVG元素的宽度/高度

Lan*_*don 73 javascript svg

获取svg元素尺寸的正确方法是什么?

http://jsfiddle.net/langdonx/Xkv3X/

Chrome 28:

style x
client 300x100
offset 300x100
Run Code Online (Sandbox Code Playgroud)

IE 10:

stylex 
client300x100 
offsetundefinedxundefined 
Run Code Online (Sandbox Code Playgroud)

FireFox 23:

"style" "x"
"client" "0x0"
"offset" "undefinedxundefined"
Run Code Online (Sandbox Code Playgroud)

有宽度和高度属性svg1,但.width.baseVal.value只有在我设置元素的宽度和高度属性时才设置.


小提琴看起来像这样:

HTML

<svg id="svg1" xmlns="http://www.w3.org/2000/svg" version="1.1">
    <circle cx="50" cy="50" r="40" stroke="black" stroke-width="1" fill="red" />
    <circle cx="150" cy="50" r="40" stroke="black" stroke-width="1" fill="green" />
    <circle cx="250" cy="50" r="40" stroke="black" stroke-width="1" fill="blue" />
</svg>
Run Code Online (Sandbox Code Playgroud)

JS

var svg1 = document.getElementById('svg1');

console.log(svg1);
console.log('style', svg1.style.width + 'x' + svg1.style.height);
console.log('client', svg1.clientWidth + 'x' + svg1.clientHeight);
console.log('offset', svg1.offsetWidth + 'x' + svg1.offsetHeight);
Run Code Online (Sandbox Code Playgroud)

CSS

#svg1 {
    width: 300px;
    height: 100px;
}
Run Code Online (Sandbox Code Playgroud)

小智 87

使用getBBox函数

http://jsfiddle.net/Xkv3X/1/

var bBox = svg1.getBBox();
console.log('XxY', bBox.x + 'x' + bBox.y);
console.log('size', bBox.width + 'x' + bBox.height);
Run Code Online (Sandbox Code Playgroud)

  • 有没有办法像HTML元素一样对待它,并获得`svg`元素占用的实际大小,尽管已经绘制了什么?http://jsfiddle.net/Xkv3X/4/ (7认同)
  • 顺便说一下,我正在尝试确定在渲染形状之前我可以绘制的画布的大小. (3认同)
  • 今天,我报告了使用符号/用法时,FireFox 38的getBoundingClientRect出现问题。在这种情况下,getBoundingClientRect将该元素扩展到viewBox的边框。此外,还有一个关于笔触宽度的已知问题。因此,getBoundingClientRect暂时不是跨浏览器解决方案。 (2认同)

小智 39

FireFox对getBBox()有疑问,我需要在vanillaJS中执行此操作.

我有一个更好的方法,与真正的svg.getBBox()函数结果相同!

有了这篇好文章:获得SVG/G元素的实际大小

var el   = document.getElementById("yourElement"); // or other selector like querySelector()
var rect = el.getBoundingClientRect(); // get the bounding rectangle

console.log( rect.width );
console.log( rect.height);
Run Code Online (Sandbox Code Playgroud)

  • 当 svg 隐藏时返回零(例如在 bootstrap 选项卡中) (2认同)

afk*_*tja 6

SVG有属性widthheight.它们返回一个SVGAnimatedLength具有两个属性的对象:animValbaseVal.此接口用于动画,其中baseVal是动画的值.从我所看到的,这个方法在Chrome和Firefox中返回一致的值,所以我认为它也可以用于获得SVG的计算大小.


Cic*_*ero 6

我正在使用Firefox,而我的工作解决方案非常接近obysky.唯一的区别是你在svg元素中调用的方法将返回多个rects,你需要选择第一个.

var chart = document.getElementsByClassName("chart")[0];
var width = chart.getClientRects()[0].width;
var height = chart.getClientRects()[0].height;
Run Code Online (Sandbox Code Playgroud)