简体   繁体   English

如何感测是否单击了HTML画布的某个区域

[英]How to sense if a certain area of an Html Canvas is clicked

I am making a game on a canvas which requires clicking a certain area of a canvas. 我在画布上制作游戏,需要单击画布的特定区域。
I need to find a way to find the coordinates of a mouse and how to sense if a cartain area is clicked. 我需要找到一种方法来查找鼠标的坐标,以及如何感测是否单击了装饰区域。
i want a command that looks like this: 我想要一个看起来像这样的命令:

    if(MouseX>20 && MouseX<40 && MouseY >20 && MouseY <40 && MouseClick==true){
alert("you clicked this area");
}

You could create an event listener for your mouse move and track you x and y coordinate. 您可以为鼠标移动创建事件监听器,并跟踪x和y坐标。 Another listener will could be created for the click event and that is when you can access if the click was in a certain location. 可以为click事件创建另一个侦听器,也就是说,如果单击位于某个特定位置,则可以访问该侦听器。

fiddle 小提琴

var mousePos = {
    x: null,
  y: null
}

document.addEventListener("mousemove", function(e) {
    mousePos.x = e.clientX;
  mousePos.y = e.clientY;
});

document.addEventListener("click", function(e) {
    console.log(mousePos);
});

Both listeners are not strictly necessary, since the clientX and clientY are both on the event of the click, but I find that it is usually good to know the location of the mouse even when the button has not just been clicked. 由于clientX和clientY都在单击时发生,因此两个侦听器都不是必需的,但是我发现,即使不只是单击按钮,通常也要知道鼠标的位置是很好的。

UPDATE 更新

I am used to dealing with full screen canvases, but it is true that the code I have put here will only give you mouse position on the document and not the canvas. 我习惯于处理全屏画布,但是的确,我在此处输入的代码只会使您在文档上鼠标位置,而不能在画布上。 .layerX and .layerY on the event object will give you the position relative to your element. 事件对象上的.layerX和.layerY将为您提供相对于元素的位置。

If you are interested just in canvas area, use this cross-browser code: 如果您只对画布区域感兴趣,请使用以下跨浏览器代码:

var canvas = document.querySelector('canvas');
canvas.addEventListener('click', function (e) {
    var MouseX = e.pageX - this.offsetLeft; 
    var MouseY = e.pageY - this.offsetTop;
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM