Get width in pixels

2

I want to get the pixel value of an svg element that is set to%. I have the following example, but returns m the value 0.

link

    
asked by anonymous 07.04.2015 / 00:36

2 answers

3

The secret is getBoundingClientRect() . It returns the desired information for some time. It works on all browsers that are not very old.

document.body.innerHTML += document.getElementById('rect').getBoundingClientRect().width;
<svg width=100% height=100%>
    <rect id=rect rx=0 ry=0 x=0 y=0 width=100% height=50px fill=HoneyDew />
</svg>    
    
07.04.2015 / 00:44
4

You can use .getBoundingClientRect() that returns an object with dimensions of the element.

In your example it would be:

{
    height: 50,
    width: 813,
    left: 8,
    bottom: 58,
    right: 821,
    top: 8
}

Example:

var el = document.getElementById('rect');
var width_plan = el.getBoundingClientRect().width
alert(width_plan);  // 821

jsFiddle: link

    
07.04.2015 / 00:42