获取SVG元素的宽度/高度

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

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

Chrome 28:
style x
client 300x100
offset 300x100

IE 10:
stylex 
client300x100 
offsetundefinedxundefined 

火狐浏览器23:
"style" "x"
"client" "0x0"
"offset" "undefinedxundefined"

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>

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);

CSS(层叠样式表)
#svg1 {
    width: 300px;
    height: 100px;
}

很好的问题。clientWidthclientHeight对我来说起到了作用。 - iPadDeveloper2011
8个回答

136

使用getBBox函数:

SVGGraphicsElement.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);

15
有没有办法像对待 HTML 元素一样处理 svg 元素,并获得它实际占用的尺寸,而不管已绘制了什么?http://jsfiddle.net/Xkv3X/4/ - Langdon
4
顺便说一下,我正在尝试确定在渲染形状之前可以绘制的画布大小。 - Langdon
1
我认为最好先检查容器的可用大小(包含您的SVG的div),然后再将适当的大小设置为您的SVG。 - Pavel Gruba
1
@Langdon 这个问题在 Firefox 中已经被修复了。Firefox 33 将会报告类似于 Chrome 的信息。 - Robert Longson
2
今天我报告了一个问题,涉及到在使用symbol/use时FireFox 38的getBoundingClientRect。在这种情况下,getBoundingClientRect会将元素扩展到viewBox的边框。此外,还存在一个关于stroke-width的已知问题。因此,目前getBoundingClientRect不是跨浏览器的解决方案。 - Dzenly
显示剩余3条评论

71

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);

这个!就像Firefox有问题,但在大多数浏览器中都可以正常工作 :) - thatOneGuy
2
当SVG被隐藏时(例如在Bootstrap选项卡中),返回零。 - Alexey Sh.
https://caniuse.com/#feat=getboundingclientrect - 现在一切看起来都很好,适用于FF12+,Chrome 4+。 - marksyzm

9

我正在使用Firefox浏览器,我的工作解决方案与obysky非常接近。唯一的区别在于,在svg元素中调用的方法将返回多个矩形,而您需要选择第一个。

var chart = document.getElementsByClassName("chart")[0];
var width = chart.getClientRects()[0].width;
var height = chart.getClientRects()[0].height;

这是在应用CSS“transform”之前获取大小的方法。 - Marko

8

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


其中 svg 是你的元素... let svgWidth = svg.width.baseVal.value ; let svgHeight = svg.height.baseVal.value ; - Bob
很遗憾,目前这在Firefox上无法工作 - 它会给您一个初始值,但如果您更改SVG尺寸并再次尝试,则会给您原始值。 - Bob

4

我发现这是一种跨浏览器的一致方法:

var heightComponents = ['height', 'paddingTop', 'paddingBottom', 'borderTopWidth', 'borderBottomWidth'],
    widthComponents = ['width', 'paddingLeft', 'paddingRight', 'borderLeftWidth', 'borderRightWidth'];

var svgCalculateSize = function (el) {

    var gCS = window.getComputedStyle(el), // using gCS because IE8- has no support for svg anyway
        bounds = {
            width: 0,
            height: 0
        };

    heightComponents.forEach(function (css) { 
        bounds.height += parseFloat(gCS[css]);
    });
    widthComponents.forEach(function (css) {
        bounds.width += parseFloat(gCS[css]);
    });
    return bounds;
};

3

从Firefox 33开始,您可以调用getBoundingClientRect(),它将正常工作,即在上面的问题中它将返回300 x 100。

Firefox 33将于2014年10月14日发布,但如果您想尝试,修复程序已经在Firefox nightlies中。


2
使用.getAttribute()方法!

var height = document.getElementById('rect').getAttribute("height");
var width = document.getElementById('rect').getAttribute("width");
var x = document.getElementById('rect').getAttribute("x");
alert("height: " + height + ", width: " + width + ", x: " + x);
<svg width="500" height="500">
  <rect width="300" height="100" x="50" y="50" style="fill:rgb(0,0,255);stroke-width:3;stroke:rgb(0,0,0)" id="rect"/>
</svg>


0

一个用于确定任何元素(无填充,无边距)宽度和高度单位的保存方法如下:

let div   = document.querySelector("div");
let style = getComputedStyle(div);

let width  = parseFloat(style.width.replace("px", ""));
let height = parseFloat(style.height.replace("px", ""));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接