Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
57
rated 0 times [  62] [ 5]  / answers: 1 / hits: 141220  / 11 Years ago, fri, august 9, 2013, 12:00:00

What is the proper way to get the dimensions of an svg element?



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



Chrome 28:



style x
client 300x100
offset 300x100


IE 10:



stylex 
client300x100
offsetundefinedxundefined


FireFox 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.






The fiddle looks like this:



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

More From » svg

 Answers
35

Use the getBBox function:



The SVGGraphicsElement.getBBox() method allows us to determine the coordinates of the smallest rectangle in which the object fits. [...]



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

[#76431] Thursday, August 8, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
cristinah

Total Points: 268
Total Questions: 113
Total Answers: 89

Location: South Korea
Member since Sat, Oct 2, 2021
3 Years ago
;