Skip to content Skip to sidebar Skip to footer

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 || ev

Solution 1:

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.


Solution 2:

For mouse coordinates (123,12) event.layerX || event.layerX == 0 will give us TRUE in the first part of the statement (event.layerX) and the second one (event.layerX == 0) won't be checked.

If event.layerX is undefined (because ie. we are using Opera) first part of the event.layerX || event.layerX == 0 will give us FALSE and the second one won't be checked.

But there is one more possibility. Mouse coordinates may be (0, 123) and the first part of event.layerX || event.layerX == 0 will give us FALSE while these coordinates are perfectly valid. That's why there is a second part event.layerX == 0 which will return TRUE so the if statement will be evaluated after all.


Post a Comment for "Return Coordinates Of Mouse Click On HTML5 Canvas Using Javascript Mouse Events?"