1 回答

TA贡献1829条经验 获得超7个赞
你想做的事是不可能的——至少不是这样。问题是画布实际上并不知道你画的东西的形状。它只知道单个像素颜色。
但是,您可以做的是将按钮的边界框 - 屏幕位置和尺寸 - 保留为 Path2D 矩形,并使用该函数context.isPointInPath(path2d,x,y)检查是否有人在画布上按钮占据的区域内单击。
这是一个示例(只需单击“运行代码片段”):
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var image = new Image();
var buttons = [];
function draw(e) {
let x, y, width, height, path;
// first button
x = 20;
y = 20;
width = 100;
height = 20;
context.drawImage(e.target, x, y, width, height);
path = new Path2D();
path.rect(x, y, width, height);
buttons.push(path);
// second button
x = 150;
y = 20;
width = 100;
height = 20;
context.drawImage(e.target, x, y, width, height);
path = new Path2D();
path.rect(x, y, width, height);
buttons.push(path);
}
function canvasClicked(e) {
let button;
for (var a = 0; a < buttons.length; a++) {
button = buttons[a];
if (context.isPointInPath(button, e.offsetX, e.offsetY)) {
console.log("button " + (a + 1) + " clicked");
}
}
}
image.onload = draw;
image.src = "https://picsum.photos/id/866/200/300";
canvas.addEventListener("click", canvasClicked);
<canvas id="canvas" style="background-color:grey;"></canvas>
添加回答
举报