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:
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.
interface DOMRect : DOMRectReadOnly { inherit attribute unrestricted double x; inherit attribute unrestricted double y; inherit attribute unrestricted double width; inherit attribute unrestricted double height; };
source share