将事件绑定到画布上 [英] Bind event to shape on canvas
本文介绍了将事件绑定到画布上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将事件绑定到画布上绘制的形状?我假设这会工作,但我得到一个错误。
How can I bind an event to a shape drawn on a canvas? I presumed this would work but I get an error.
<html>
<head>
<script type="application/javascript">
function draw() {
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "rgb(200,0,0)";
var rec = ctx.fillRect (0, 0, 55, 50);
rec.onclick = function(){
alert('something');
}
}
</script>
</head>
<body onLoad="draw()">
<canvas id="canvas" width="300" height="300"></canvas>
</body>
</html>
推荐答案
将事件处理程序放在canvas元素上,然后使用鼠标位置来决定画布上哪个概念部分发生了事件。
Put the event handlers on the canvas element, and then use the mouse position to decide which conceptual part of the canvas the event is occurring on.
我没有使用画布这么多,但我不会如果已经有一些图书馆帮助你管理事件委托这样虚构的元素,惊讶。
I haven't played with canvas all that much, but I wouldn't be surprised if there were already some libraries that help you manage event delegation to such imaginary elements.
这篇关于将事件绑定到画布上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文