javascript - In google chrome, getBoundingClientRect().x is undefined -


i'm performing drawing operations on canvas. best way calculate cursor position relative canvase top left corner is, in opinion, usage of .getboundingclientrect():

htmlcanvaselement.prototype.relativecoords = function(event) {   var x,y;   //this current screen rectangle of canvas   var rect = this.getboundingclientrect();    //recalculate mouse offsets 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 array   return [x,y]; } 

i see nothing wrong code , works in firefox. test it.

in google chrome however, debug line prints this:

x(nan) = event.clientx(166) - rect.x(undefined)

what doing wrong? is not according specifications?

edit: seems code follows w3c:

from specs:

getboundingclientrect()

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

  1. let list result of invoking getclientrects() on same element method invoked on.

  2. if list empty return domrect object x, y, width , height members zero.

  3. otherwise, return domrect object describing smallest rectangle includes first rectangle in list , of remaining rectangles of height or width 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; }; 

the object returned getboundingclientrect() may have x , y properties in browsers, not all. has left, top, right, , bottom properties.

i recommend using mdn docs instead of w3c specs when want know browsers implement. see mdn docs getboundingclientrect() more accurate information on function.

so need change rect.x , rect.y rect.left , rect.top.


Comments

Popular posts from this blog

javascript - Any ideas when Firefox is likely to implement lengthAdjust and textLength? -

matlab - "Contour not rendered for non-finite ZData" -

delphi - Indy UDP Read Contents of Adata -