Skip to content
Advertisement

getBoundingClientRect() returns inaccurate values for complex SVG’s in Chrome

I’m trying to calculate the bounding box of transformed SVG elements and for that I’m using getBoundingClientRect() and mapping the x and y values to SVG coordinates. However, this function seems to produce wrong outputs in Chrome and Edge when the shape has curves and a rotation. In the other hand, Firefox is able to produce the expected result.

Here’s an example.

JavaScript

Is there any way to achieve this with more precision like Firefox?

Advertisement

Answer

I deleted my previous answer as it was plain wrong, hope this is a better one:

JavaScript

The SVGRect returned by getBBox is identical Firefox/Chromium. However as stated here on MDN

The returned value is a SVGRect object, which defines the bounding box. This value is irrespective of any transformation attribute applied to it or the parent elements

So you always get the bounding box of the svg before tranforms are applied this way. If you use getBoundingClientRect to get a DOMRect you will find out that Chrome seems to just apply the transforms on the original bounding rect and then calculate the bounding box of that.

enter image description here

You would achieve the same with something like this (more or less useless code just for illustration):

JavaScript

Or you could just check the Developer tools of Firefox/Chromium to see the dfifferences (just to say putting a group around doesn’t work either).

Maybe SVG version 2 will make a difference in the future: Chrome Platfor Status SVG2

So now what? If getBBox is the only function that seems to be working but only for svgs without inner transforms, can these transforms be applied dynamically with javascript?

Turns out someone went the extra mile: flatten.js

put the script in a file ‘flatten.js’ and remove the leftovers at the top if still there (html, title..)

JavaScript

enter image description here

enter image description here

So this might be a workaround way to get the “real” bounding box.

As for getBoundingClientRect: MDN says: “The returned value is a DOMRect object which is the smallest rectangle which contains the entire element, including its padding and border-width.”

IMHO there is a bug in Chromium’s implementation.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement