简体   繁体   English

获取 SVG 元素的宽度/高度

[英]Get width/height of SVG element

What is the proper way to get the dimensions of an svg element?获取svg元素尺寸的正确方法是什么?

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

Chrome 28:铬 28:

style x
client 300x100
offset 300x100

IE 10: IE 10:

stylex 
client300x100 
offsetundefinedxundefined 

FireFox 23:火狐 23:

"style" "x"
"client" "0x0"
"offset" "undefinedxundefined"

There are width and height properties on svg1 , but .width.baseVal.value is only set if I set the width and height attributes on the element. svg1上有 width 和 height 属性,但只有在我在元素上设置 width 和 height 属性时才设置.width.baseVal.value


The fiddle looks like this:小提琴看起来像这样:

HTML 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 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 CSS

#svg1 {
    width: 300px;
    height: 100px;
}

Use the getBBox function:使用getBBox函数:

The SVGGraphicsElement.getBBox() method allows us to determine the coordinates of the smallest rectangle in which the object fits. SVGGraphicsElement.getBBox()方法允许我们确定对象适合的最小矩形的坐标。 [...] [...]

http://jsfiddle.net/Xkv3X/1/ 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);

FireFox have problemes for getBBox(), i need to do this in vanillaJS. FireFox 对 getBBox() 有问题,我需要在 vanillaJS 中执行此操作。

I've a better Way and is the same result as real svg.getBBox() function !我有更好的方法,结果与真正的 svg.getBBox() 函数相同!

With this good post : Get the real size of a SVG/G element有了这篇好文章: 获取 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);

I'm using Firefox, and my working solution is very close to obysky.我正在使用 Firefox,我的工作解决方案非常接近 obysky。 The only difference is that the method you call in an svg element will return multiple rects and you need to select the first one.唯一的区别是您在 svg 元素中调用的方法将返回多个矩形,您需要选择第一个。

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

SVG has properties width and height . SVG 具有属性widthheight They return an object SVGAnimatedLength with two properties: animVal and baseVal .它们返回一个具有两个属性的对象SVGAnimatedLengthanimValbaseVal This interface is used for animation, where baseVal is the value before animation.该接口用于动画,其中baseVal为动画的值。 From what I can see, this method returns consistent values in both Chrome and Firefox, so I think it can also be used to get calculated size of SVG.据我所知,这个方法在 Chrome 和 Firefox 中返回一致的值,所以我认为它也可以用来计算 SVG 的大小。

This is the consistent cross-browser way I found:这是我发现的一致的跨浏览器方式:

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

From Firefox 33 onwards you can call getBoundingClientRect() and it will work normally, ie in the question above it will return 300 x 100.从 Firefox 33 起,您可以调用 getBoundingClientRect() 并且它会正常工作,即在上面的问题中它将返回 300 x 100。

Firefox 33 will be released on 14th October 2014 but the fix is already in Firefox nightlies if you want to try it out. Firefox 33 将于 2014 年 10 月 14 日发布,但如果您想尝试一下,该修复程序已经在Firefox nightlies中了。

Use .getAttribute()!使用 .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>

A save method to determine the width and height unit of any element (no padding, no margin) is the following:确定任何元素的宽度和高度单位(无填充,无边距)的保存方法如下:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM