使用 Javascript 鼠标事件返回鼠标在 HTML5 画布上单击的坐标?
请参阅 此站点
我想返回鼠标单击/移动相对于 html5 画布的相对坐标。下面的代码是什么意思?
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 适用于除 Opera 之外的所有浏览器。 offsetX 适用于除 Firefox 之外的所有浏览器
那么,如果 event.layerX 或 event.layerY 为 0,我们的意思是什么... 我的意思是 event.layerX 返回鼠标单击画布的相对坐标。那么这有什么意义呢?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
更好的方法是这样的代码:
它简短、正确并且
The better way is such code:
It is shortly, correct, and
对于鼠标坐标 (123,12)
event.layerX || event.layerX == 0
将在语句的第一部分 (event.layerX
) 和第二部分 (event.layerX == 0
) 中为我们提供 TRUE >) 不会被检查。如果 event.layerX 未定义(因为我们使用的是 Opera),则 event.layerX || 的第一部分event.layerX == 0 会给我们 FALSE 并且第二个不会被检查。
但还有一种可能性。鼠标坐标可能是 (0, 123) 和 event.layerX || 的第一部分event.layerX == 0 会给我们 FALSE,而这些坐标完全有效。这就是为什么有第二部分
event.layerX == 0
它将返回 TRUE,因此 if 语句最终将被评估。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 theevent.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 partevent.layerX == 0
which will return TRUE so the if statement will be evaluated after all.