Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get SVG element dimensions in FireFox?

Tags:

firefox

svg

In most browsers, the following would work.

window.onload = function(){
    console.log( document.getElementById('svgElm').getBoundingClientRect().width );
};

Here is a demo. If you try it in Google Chrome, the console will output 200. However, FireFox returns 0.

like image 812
Gajus Avatar asked Oct 29 '12 13:10

Gajus


People also ask

How do I get SVG width and height?

To get width and height of SVG element with JavaScript, we can use the getBoundingClientRect method. const el = document. getElementById("yourElement"); const rect = el. getBoundingClientRect(); console.

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.

How do I set SVG dimensions?

Any height or width you set for the SVG with CSS will override the height and width attributes on the <svg> . So a rule like svg {width: 100%; height: auto;} will cancel out the dimensions and aspect ratio you set in the code, and give you the default height for inline SVG.

Do SVG images have dimensions?

The thing is: SVG images don't have a "size" in the sense you are probably thinking of. On the other hand, they DO have a height-to-width ratio. This ratio can usually be found in the viewBox attribute.


1 Answers

I've ended up falling back to the parent dimensions if SVG properties cannot be returned. Here is a demo http://jsbin.com/uzoyik/1/edit.

The relavent code is:

svg.clientWidth || svg.parentNode.clientWidth
svg.clientHeight || svg.parentNode.clientHeight
like image 178
Gajus Avatar answered Oct 06 '22 06:10

Gajus