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

梦想与她 提交于 2019-12-23 12:12:39

问题


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?


回答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.




回答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.



来源:https://stackoverflow.com/questions/8878471/return-coordinates-of-mouse-click-on-html5-canvas-using-javascript-mouse-events

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!