Skip to content Skip to sidebar Skip to footer

In Javascript, Why Does Getboundingclientrect() Sometimes Return Floating Point Values?

I'm trying to work with an HTML5 canvas element. One thing i'm trying to do is set up a mousemove event to track the mouse on the canvas for drawing and other purposes. I have not

Solution 1:

tldr; you did zoom/unzoom in your browser.

The problem

margin-left: 30px;

In this jsfiddle thats mimics your problem it does not works as you said on my computer when navigator zoom is set to 100% (normal). But if you zoom inside your browser you will notice such behavior.

margin-left: 11%;

Instead if you use % margin like in this jsfiddle you will notice it does returns floating mouse position wether zoom is on or not.

The answer

The thing is mouse position is computed as it appears on the screen : it may only have entire position coordinates since it is pixel based.

However getBoundingClientRect returns what browser computes to be "Bounding Client Rect of the element" after applying margins, zoom and others modifiers but before telling the GPU to render it. In short it returns the real position of the element which is later approximated by the GPU to be rendered within a matrix of pixels. If you use pixel margins/sizes/paddings/etc then elements positions remains integer based, but if you zoom or use em/% positioning values then it may result floating positions.

The solutions

  1. round bounds
  2. assume it is indeed a floating position and it's just the GPU that needs to round it in order to make it fit on the screen

Edit : The forgotten solutions

Post a Comment for "In Javascript, Why Does Getboundingclientrect() Sometimes Return Floating Point Values?"