如何在鼠标单击矩形时执行函数 HTML5 Canvas

How to execute a function on mouse click on rectangle HTML5 Canvas

我正在寻找一种简单的方法来在有人单击 HTML5 Canvas 内的矩形时执行函数。我想以不需要任何特殊库的方式进行。有什么建议吗?

这是一种无库方式,涉及:

  1. 侦听 mousedown 事件:

    var canvas=document.getElementById("canvas");
    
    canvas.onmousedown=handleMousedown;
    
  2. 测试鼠标点击位置是否在矩形内:

    var rect={x:100,y:100,w:75,h:40};
    
    // mx & my are the mouse coordinates
    if(mx>=rect.x && mx<=rect.x+rect.w && my>=rect.y && my<=rect.y+rect.h){
            alert("clicked in rect");
    }
    

这是示例代码和演示:

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var BB,BBoffsetX,BBoffsetY;
setBB();

var rect={x:100,y:100,w:75,h:40};

ctx.fillRect(rect.x,rect.y,rect.w,rect.h);


canvas.onmousedown=handleMousedown;

function handleMousedown(e){
  e.preventDefault();
  e.stopPropagation();
  var mx=e.clientX-BBoffsetX;
  var my=e.clientY-BBoffsetY;
  if(mx>=rect.x && mx<=rect.x+rect.w && my>=rect.y && my<=rect.y+rect.h){
    alert("clicked in rect");
  }
}

function setBB(){
  BB=canvas.getBoundingClientRect();
  BBoffsetX=BB.left;
  BBoffsetY=BB.top;
}
body{ background-color: ivory; }
canvas{border:1px solid red;}
<h4>Click in the rect for an alert</h4>
<canvas id="canvas" width=300 height=300></canvas>