Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return coordinates of mouse click on HTML5 canvas using Javascript mouse events?

See the code on this site

I want to return the relative coordinates of a mouse click/move with respect to the html5 canvas. What does the code below mean?

if ( event.layerX ||  event.layerX == 0) { // Firefox
            mouseX = event.layerX ;
            mouseY = event.layerY;
} else if (event.offsetX || event.offsetX == 0) { // Opera
            mouseX = event.offsetX;
            mouseY = event.offsetY;
}

layerX works on all browsers except Opera. offsetX works on all browsers except Firefox

So what do we mean by, if either event.layerX OR event.layerY is 0... I mean event.layerX returns relative coordinates of mouse click w.r.t canvas. So how does this make any sense?

like image 300
P.C. Avatar asked Feb 22 '23 19:02

P.C.


1 Answers

The better way is such code:

if ( event.offsetX == null ) { // Firefox
   mouseX = event.originalEvent.layerX;
   mouseY = event.originalEvent.layerY;
} else {                       // Other browsers
   mouseX = event.offsetX;
   mouseY = event.offsetY;
}

It is shortly, correct, and

event.layerX and event.layerY are broken and deprecated in WebKit. They will be removed from the engine in the near future.

like image 189
Shock Avatar answered Feb 24 '23 10:02

Shock