[英]Adding an Event Listener to the Canvas
这不应该是一个问题,但我无法弄清楚为什么我的事件监听器没有触发。 我已经在这里将我的代码剥离到几乎裸露的地方,但它仍然不会很好。
突然出现的唯一变量是我正在使用 jQuery 的 jCanvas,但我怀疑这就是问题所在。
这是代码:
jQuery(document).ready(function(){
// Get the Canvas set to the proper size
canvas = document.getElementById("background");
canvas.width = document.width;
canvas.height = document.height;
canvasW = canvas.width;
canvasH = canvas.height;
canvas.addEventListener("mousedown", check,false);
});
function check(ev)
{
alert('click');
}
我认为你的代码有效。 这就是我尝试过的 http://jsfiddle.net/QXSsE/1/
jQuery(document).ready(function() {
// Get the Canvas set to the proper size
canvas = document.getElementById("background");
var context = canvas.getContext('2d');
if (context) {
// You are done! Now you can draw your first rectangle.
// You only need to provide the (x,y) coordinates, followed by the width and
// height dimensions.
context.fillRect(0, 0, 150, 100);
}
canvas.addEventListener("mousedown", check, false);
});
function check(ev) {
alert('click');
}
好吧,在您在其他答案的评论中给出的链接中,您显然在后台有 canvas。 如果元素在另一个元素下,则无法触发事件。 您的 canvas 的z-index
为0
,将其保持在body
下方。 使用控制台,我只是更改了z-index
,它工作得很好。
在相关说明中,您可能已经看到 Google让它下雪canvas 的事情。 如果您注意到,一开始您无法与雪互动。 它的z-index
很低。 过了一会z-index
变大了,不能和文字交互了; 只有雪。
如您所见,这与您使用 canvas 无关。 这只是元素相互放置时事件的工作方式。 简单的例子说明我的观点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.