Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate size of SVG element in HTML page

Tags:

html

firefox

svg

How can I reliably ask for the size (in pixels) an SVG element is taking up on the host page?

  • Both svg.offsetWidth and svg.getBoundingClientRect().width work in Chrome v34.
  • Neither of those work correctly in Firefox v29. (The former is empty, the latter returns incorrect values.)

Test Page: http://jsfiddle.net/dL5pZ/3/

The motivation for this question is to get a reliable implementation for this answer, which requires knowing the aspect ratio of the outside of the element. Further, for this question I need to know the actual size of the SVG, or at least something that returns proportionate values across different calls and a resizing element.

like image 648
Phrogz Avatar asked May 15 '14 17:05

Phrogz


1 Answers

I've been down that road before. Unfortunately, most of the functions for getting the size of the <svg> element are buggy in Firefox. The only working solution I found was using window.getComputedStyle(svgElement).width (or height), which needs to be parsed (and also only works when svgElement.display == 'block', which it is in your example). I have adopted your fiddle to work in Firefox: http://jsfiddle.net/dL5pZ/5/

Update: The issue with display 'inline' was fixed some time ago around Firefox 29.

Update 2: As mentioned in another answer, getBoundingClientRect should also work nowadays.

like image 117
ernesto Avatar answered Oct 08 '22 00:10

ernesto