5

The implementation of getBoundingClientRect() varies from browser to browser when it comes to a SVG path with a given stroke width, with browsers like Firefox including the stroke width (unlike Chrome, for instance).

By "including the stroke width" I'd expect just that, the bounding box containing the path with its stroke but nothing else. However, as you can see in this basic example, it seems that in Firefox the stroke-width is creating an additional border around the whole element, with twice the value of the stroke-width itself:

console.log(document.querySelector("path").getBoundingClientRect())
path {
  stroke: black;
  stroke-width: 30px;
}
<svg>
  <path d="M0,20 L300,20"></path>
</svg>

This is a screenshot of the very snippet above, inspecting the element:

enter image description here

As you can see, not only getBoundingClientRect() but even the dev tools inspector is getting the bounding rect wrong (420x120 instead of 300x30. It's worth mentioning that Chrome and Safari will return 300x0, as described in the first paragraph).

Is this the expected behaviour?

  • 2
    [Yes](https://lists.w3.org/Archives/Public/www-style/2011Aug/0120.html), this is the behaviour we intended to implement. – Robert Longson Aug 14 '20 at 07:21
  • @RobertLongson Thanks for your comment, but I already know that: I'm linking your message in my question. My question is: why is the bounding box way bigger than the stroke width? To put it another way: in my example the path's box can be `300x0` (no decoration) or `300x30` (with decoration), but why is it `420x120`? –  Aug 14 '20 at 09:10
  • 1
    @RobertLongson if I understand correctly your point there, IE and FF were basically using the pointer-events' "painted" area to calculate that bounding box, right? Then I don't understand where does the `width: 420` comes from. The width of the "painted" area is still 300px. Maybe [this fiddle](https://jsfiddle.net/zo23kbnc/) better exposes the discrepancy? There, both the rect and the path should have the same bounding box in FF according to my understanding of your message. – Kaiido Aug 14 '20 at 09:13
  • Yes, @Kaiido nailed my problem. –  Aug 14 '20 at 09:14
  • It's hard to calculate an accurate bounding box because the path might be bent and the bends could poke out so we calculate a bounding box that guarantees to be large enough. The code is [here](https://searchfox.org/mozilla-central/source/layout/svg/SVGUtils.cpp#1293). If you think you can do better, patches are always welcome! – Robert Longson Aug 14 '20 at 09:23
  • Doesn't hit test algo calculate it more precisely? I guess it's fast enough for gBCR. – Kaiido Aug 14 '20 at 09:29
  • @RobertLongson Thanks, now I have an answer! Well, I'll just try a workaround... out of curiosity, what language is that? C++? –  Aug 14 '20 at 09:32
  • 1
    Firefox is written in C++, javascript and rust. That part is C++ – Robert Longson Aug 14 '20 at 09:43

0 Answers0