检测画布游戏中的鼠标左右事件

7

我想使用纯粹的JavaScript实现一个Canvas 扫雷游戏。 我使用了二维数组来创建网格。在游戏中,我需要检测左右鼠标点击事件,每个事件将执行不同的操作。我的研究指向了mousedownmouseupcontextmenu事件,但是我的代码似乎不能正常运行,因为鼠标右键单击也会触发mouseup事件。有谁能帮我理解如何区分这两种事件? 我看到了一些示例,使用了event.which,其中左键单击是event.which === 0,右键单击是event.which === 2,但是只适用于按钮,就我所知。

 canvas.addEventListener('mouseup', function(evt) {
    let x1 = Math.floor(evt.offsetX/(canvas.height/rows));
    let y1 = Math.floor(evt.offsetY/(canvas.width/cols));
    draw (y1, x1); //this is my drawing functions (draws the numbers, bombs)

}, false); 

canvas.addEventListener('contextmenu', function(evt) {
    let j = Math.floor(evt.offsetX/(canvas.height/rows));
    let i = Math.floor(evt.offsetY/(canvas.width/cols));

    ctx.drawImage(flagpic, j*widthCell+5, i*widthCell+2, widthCell-9, 
    widthCell-5); //draws the flag where right mouse clicked

}, false);

可能是 右键点击是Javascript事件吗? 的重复。 - Tigger
2个回答

20

使用click事件处理左键点击:

canvas.addEventListener('click', function(evt) { // No right click

使用 contextmenu 实现右键菜单:(通过键盘上下文菜单实现鼠标右键单击)

canvas.addEventListener('contextmenu', function(evt) { // Right click

你还需要调用evt.preventDefault()来防止默认操作。


在你的情况下,如果你想使用mousedown或mouseup事件,那么你可以使用event.button来检测点击的按钮是否是左键:

canvas.addEventListener('mousedown', function(evt) {
  if(evt.button == 0) {
    // left click
  }

这里是按钮点击的值:

left button=0, 
middle button=1 (if present),
right button=2

您可以查看以下链接中显示的示例以获取更详细的信息: MouseEvent.button
<script>
var whichButton = function (e) {
    // Handle different event models
    var e = e || window.event;
    var btnCode;

    if ('object' === typeof e) {
        btnCode = e.button;

        switch (btnCode) {
            case 0:
                console.log('Left button clicked.');
            break;

            case 1:
                console.log('Middle button clicked.');
            break;

            case 2:
                console.log('Right button clicked.');
            break;

            default:
                console.log('Unexpected code: ' + btnCode);
        }
    }
}
</script>

<button onmouseup="whichButton(event);" oncontextmenu="event.preventDefault();">
    Click with mouse...
</button>

2
"contextmenu"和"right click"是两个不同且无关的事件。"contextmenu"可以通过某些键盘、鼠标+键的组合以及其他方式触发。 - Kaiido

2

你可以尝试这个方法,也许对你有用。

document.getElementById("mydiv").onmousedown = function(event) {
 myfns(event)
};

var myfns = function(e) {

  var e = e || window.event;
  var btnCode;

  if ('object' === typeof e) {
    btnCode = e.button;

    switch (btnCode) {
      case 0:
        console.log('Left');
        break;

      case 1:
        console.log('Middle');
        break;

      case 2:
        console.log('Right');
        break;

    }
  }
}
<div id="mydiv">Click with mouse...</div>

Reference

https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button


啊不好意思...我的意思是请使用addEventListener代替<div onXXX="uglyJS">。并且阻止默认的上下文菜单行为是很好的。 - Kaiido

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接