Reputation: 664
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
Upvotes: 1
Views: 4433
Reputation: 12764
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).
Upvotes: 1