检测 Canvas 游戏的左右鼠标事件

Detecting Left and Right Mouse Events for a Canvas Game

我想实现一个 canvas 扫雷 游戏 javascript。我为我的网格使用二维数组。对于游戏,我需要检测鼠标右键和左键点击,每一次都会做不同的事情。我的研究将我引向 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);

左键单击使用 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

您可以查看下面link中显示的示例以了解更多详细信息:

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>

试试这个可能对你有用

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>

参考

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