如何使用JavaScript触发Canvas中按钮的点击事件



我在谷歌上搜索了几个小时,但没有得到任何答案。我正在尝试触发Canvas中某个按钮的点击事件。源代码如下所示:

<body>
<div class="webgl">
<div id="unity">
<canvas id="canvas"></canvas>
</div>
</div></body>

我够不到按钮元件。我不知道是否有解决方案。你能帮我吗?

我们不能将事件处理程序附加到画布内绘制的路径,但我们可以将事件附加到整个画布,获取x、y坐标,并查明用户是否单击了画布内的按钮。您可以运行以下代码,其中我创建了2个按钮,并在整个画布元素上附加了一个点击处理程序。在这个处理程序中,我正在收集事件坐标,并使用一些数学方法来确定点击是否真的发生在按钮上。

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// create circles to draw
const buttons = [
{
x: 40,
y: 40,
width: 100,
height: 40,
color: 'rgb(255,0,0)',
text: 'Button 1'
},
{
x: 40,
y: 100,
width: 100,
height: 40,
color: 'rgb(255,0,255)',
text: 'Button 2'
}
];
buttons.forEach(b => {
ctx.beginPath();
ctx.rect(b.x, b.y, b.width, b.height);
ctx.fillStyle = b.color;
ctx.fill();
ctx.fillStyle = 'white';
ctx.font = "14px Arial";
ctx.fillText(b.text, b.x + b.width / 4, b.y + b.height / 1.6);
});
function isIntersect(pos, btn){
if( 
(pos.x >= btn.x && pos.x < btn.x + btn.width) &&
(pos.y >= btn.y && pos.y < btn.y + btn.height)
)
return true;
return false;
}
canvas.addEventListener('click', (e) => {
const pos = {
x: e.clientX,
y: e.clientY
};
buttons.forEach((b,i) => {
if (isIntersect(pos, b)) {
alert('click on circle: ' + i);
}
});
});
body {
margin: 0;
padding: 0;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
canvas{
border: 1px solid red;
}
<canvas id="canvas" />

最新更新