Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get width/height of SVG element

Tags:

javascript

svg

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; } 
like image 259
Langdon Avatar asked Aug 09 '13 13:08

Langdon


People also ask

How do you find the width of an SVG text element?

To get text element width of an SVG with JavaScript, we can use the getBBox method. const bbox = textElement. getBBox(); const width = bbox. width; const height = bbox.

What is a viewBox SVG?

The viewBox is an attribute of the SVG element in HTML. It is used to scale the SVG element that means we can set the coordinates as well as width and height. Syntax: viewBox = "min-x min-y width height" Attribute Values: min-x: It is used to set the horizontal axis.

What is SVG height?

For <svg> , height defines the vertical length for the rendering area of the SVG viewport. Note: Starting with SVG2, height is a Geometry Property meaning this attribute can also be used as a CSS property for <svg> .


1 Answers

Use getBBox function

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); 
like image 188
Pavel Gruba Avatar answered Sep 19 '22 09:09

Pavel Gruba