【问题标题】:Get width/height of SVG element获取 SVG 元素的宽度/高度
【发布时间】:2013-08-11 10:59:34
【问题描述】:

获取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 和 height 属性,但 .width.baseVal.value 只有在我设置元素的 width 和 height 属性时才会设置。


小提琴看起来像这样:

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

【问题讨论】:

    标签: javascript svg


    【解决方案1】:

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

    【讨论】:

    • 有没有办法将其视为 HTML 元素并获得 svg 元素占用的实际大小,尽管已经绘制了什么? jsfiddle.net/Xkv3X/4
    • 顺便说一句,我正在尝试确定在渲染形状之前可以绘制的画布大小。
    • 我认为检查容器的可用大小(包含您的 svg 的 div)可能会更好,然后您可以为您的 svg 设置适当的大小
    • @Langdon 刚刚在 Firefox 中修复。 Firefox 33 将报告类似于 Chrome 的内容。
    • 今天我报告了在使用符号/使用时 getBoundingClientRect for FireFox 38 的问题。在这种情况下,getBoundingClientRect 将元素扩展到 viewBox 的边框。还有一个关于笔划宽度的已知问题。所以 getBoundingClientRect 目前还不是跨浏览器解决方案。
    【解决方案2】:

    FireFox 的 getBBox() 有问题,我需要在 vanillaJS 中执行此操作。

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

    有了这个好帖子:Get the real size of a SVG/G element

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

    【讨论】:

    【解决方案3】:

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

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

    【讨论】:

    • 这是在应用 CSS transform 之前获取大小的方法。
    【解决方案4】:

    SVG 具有属性widthheight。它们返回一个具有两个属性的对象SVGAnimatedLengthanimValbaseVal。该接口用于动画,其中baseVal是动画before的值。据我所知,这个方法在 Chrome 和 Firefox 中返回的值是一致的,所以我认为它也可以用来计算 SVG 的大小。

    【讨论】:

    • 其中 svg 是你的元素... let svgWidth = svg.width.baseVal.value ;让 svgHeight = svg.height.baseVal.value ;
    • 不幸的是,目前这在 Firefox 上不起作用 - 它会为您提供初始值,但如果您更改 svg 尺寸并再次尝试,它会为您提供原始值。
    【解决方案5】:

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

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

    【讨论】:

      【解决方案6】:

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

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

      【讨论】:

        【解决方案7】:

        确定任意元素(无内边距、无边距)的宽高单位的保存方法如下:

        let div   = document.querySelector("div");
        let style = getComputedStyle(div);
        
        let width  = parseFloat(style.width.replace("px", ""));
        let height = parseFloat(style.height.replace("px", ""));
        

        【讨论】:

          【解决方案8】:

          使用 .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>

          【讨论】:

            猜你喜欢
            • 2019-04-11
            • 2018-01-12
            • 2010-12-10
            • 1970-01-01
            • 2017-01-31
            • 2015-12-24
            • 1970-01-01
            • 2021-04-03
            相关资源
            最近更新 更多