1

I have some inconsistencies when trying to draw some lines between elements that I find on the DOM using CSS selectors, and believe it may be to do with the method I am calling getBoundingClientRect().

If anybody could provide any information about how the top, left, bottom, right are calculated for a boundingClientRect, specifically with respect to HTML canvases I would really appreciate it.

An example of an inconsistency I am getting is that when I do canvas.getBoundingClientRect().top I get 70. Then I have an element in the DOM which I find and calculates its top, which is 334. When I subtract the two to find the offset (334 - 70 = 264), however when I draw a grid on the canvas I can clearly see that the element is greater than 275, almost 280.

I think the real question is, does this method always give a top and a bottom with respective to the same rect, as this is the only explanation I can come up with for the inconsistencies.

Thanks

Zoltán Tamási
  • 12,249
  • 8
  • 65
  • 93
SwimmingG
  • 654
  • 2
  • 9
  • 29
  • 2
    [The MDN#Value](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect#Value) May be of help. – ste2425 Sep 08 '16 at 14:57

1 Answers1

1

The getBoundingClientRect returns coordinates relative to the viewport. It means that it doesn't take window (body) scroll position into account.

Properties other than width and height are relative to the top-left of the viewport.

For example, if the window is scrolled down by 10px, you have to add 10 to the returned top value to get the element top-left corner coordinates relative to the document top-left corner.

Maybe your window was scrolled and that messed up your calculations.

If you use jQuery, you can use its offset method, which returns coordinates relative to the document top-left corner, and by the way, uses getBoundingClientRect internally (at least newer versions).

Arun Kumar Mohan
  • 11,517
  • 3
  • 23
  • 44
Zoltán Tamási
  • 12,249
  • 8
  • 65
  • 93
  • 1
    This was a good point, but didn't solve the problem, the solution was to do with scaling and I urge people using HTML canvas to be very careful about making sure they set the canvas attributes as shown in this answer. http://stackoverflow.com/questions/3185631/strange-html5-canvas-drawimage-behaviour – SwimmingG Sep 09 '16 at 22:26
  • Ok I'm glad you found the solution. – Zoltán Tamási Sep 10 '16 at 06:24