Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In google chrome, getBoundingClientRect().x is undefined

I'm performing drawing operations on canvas. The best way to calculate cursor position relative to canvase top left corner is, in my opinion, usage of .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 see nothing wrong with this code and it works in firefox. Test it.

In google chrome however, my debug line prints this:

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

What am I doing wrong? Is this not according to the specifications?

Edit: seems my code follows W3C:

From the specs:

getBoundingClientRect()

The getBoundingClientRect() method, when invoked, must return the result of the following algorithm:

  1. Let list be the result of invoking getClientRects() on the same element this method was invoked on.

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

  3. Otherwise, return a DOMRect object describing the smallest rectangle that includes the first rectangle in list and all of the remaining rectangles of which the height or width is not 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;
};
like image 607
Tomáš Zato - Reinstate Monica Avatar asked Nov 27 '14 11:11

Tomáš Zato - Reinstate Monica


People also ask

What does getBoundingClientRect() do?

The getBoundingClientRect() method returns the size of an element and its position relative to the viewport. The getBoundingClientRect() method returns a DOMRect object with eight properties: left, top, right, bottom, x, y, width, height.

What is element getBoundingClientRect ()?

The Element. getBoundingClientRect() method returns a DOMRect object providing information about the size of an element and its position relative to the viewport.


1 Answers

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

I recommend using the MDN docs instead of any W3C specs when you want to know what browsers actually implement. See the MDN docs for getBoundingClientRect() for more accurate information on this function.

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

like image 114
Michael Geary Avatar answered Sep 18 '22 12:09

Michael Geary