当有人点击HTML5 Canvas中的矩形时,我正在寻找一种简单的方法来执行某个功能。我想以一种不需要任何特殊库的方式来实现。有什么建议吗?
答案 0 :(得分:0)
这是一种无库的方式,涉及:
倾听mousedown事件:
var canvas=document.getElementById("canvas");
canvas.onmousedown=handleMousedown;
测试点击的鼠标位置是否在矩形内:
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>