HTML5 Canvas鼠标坐标 [英] HTML5 Canvas Mouse coordinates
问题描述
我有一个带有< canvas>
元素的HTML文件,我试图在点击$ c中获取鼠标坐标$ c>事件。我正在使用此代码:
I have an HTML file with a <canvas>
element and I am trying to get the mouse coordinates in the click
event. I am using this code:
secondCanvas.addEventListener('click', function(e) {
console.log(e.pageX)
}, false);
当我点击左上角时,我进入控制台500~数字,而不是零......我需要做什么才能在画布上获得鼠标的坐标?
When I click on the top left point I get in console 500~ number, not zero... what do I need to do to get the coordinates of the mouse on the canvas?
推荐答案
您应该通过以下方式计算画布鼠标的位置从事件偏移量( e.pageX
和 e.pageY
)中减去canvas元素偏移量。
这是一个链接,解释了如何获取元素在dom中的位置,代码应如下所示:
You should calculate the canvas mouse position by substracting the canvas element offset from the event offset (e.pageX
and e.pageY
).
Here's a link that explains how to get an element position in the dom, and the code should look like :
secondCanvas.addEventListener('click', function(e) {
var pos = {
x : e.pageX - canvasOffsetX,
y : e.pageY - canvasOffsetY
};
console.log(pos.x)
}, false);
这篇关于HTML5 Canvas鼠标坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!