In google chrome, getBoundingClientRect (). X is undefined

I perform drawing operations on canvas. The best way to calculate the position of the cursor relative to the upper left corner of the canvas is, in my opinion, using .getBoundingClientRect() :

 HTMLCanvasElement.prototype.relativeCoords = function(event) { var x,y; //This is the current screen rectangle of canvas var rect = this.getBoundingClientRect(); //Recalculate mouse offsets to relative offsets x = event.clientX - rect.x; y = event.clientY - rect.y; //Debug console.log("x(",x,") = event.clientX(",event.clientX,") - rect.x(",rect.x,")"); //Return as array return [x,y]; } 

I do not see anything wrong with this code, and it works in firefox. Check it out.

However in google chrome my debug line prints this:

x ( NaN ) = event.clientX ( 166 ) - rect.x ( undefined )

What am I doing wrong? Is this not in accordance with the specifications?

Edit: it seems my code follows W3C:

From the specifications:

getBoundingClientRect()

The getBoundingClientRect() method, when called, should return the result of the following algorithm:

  • Let the list be the result of calling getClientRects() on the same element to which this method was called.

  • If the list is empty, return a DOMRect object whose members x , y , width and height are zero.

  • Otherwise, return a DOMRect object describing the smallest rectangle that includes the first rectangle in the list, and all remaining rectangles whose height or width is non-zero.

DOMRect

 interface DOMRect : DOMRectReadOnly { inherit attribute unrestricted double x; inherit attribute unrestricted double y; inherit attribute unrestricted double width; inherit attribute unrestricted double height; }; 
+6
source share
2 answers

The object returned by getBoundingClientRect() may have the x and y properties in some browsers, but not all. It always has left , top , right and bottom properties.

I recommend using MDN docs instead of any W3C specs when you want to know which browsers actually implement. For more precise information about this function, see MDN docs for getBoundingClientRect () .

So all you have to do is change your rect.x and rect.y to rect.left and rect.top .

+12
source

You define it like that.

 var rect.x = this.getBoundingClientRect().width; var rect.y = this.getBoundingClientRect().height; 
-3
source

Source: https://habr.com/ru/post/978783/


All Articles