简体   繁体   English

向 Canvas 添加事件监听器

[英]Adding an Event Listener to the Canvas

This shouldn't be an issue, but I can't figure out why my event listener isn't firing.这不应该是一个问题,但我无法弄清楚为什么我的事件监听器没有触发。 I've stripped my code to near bare bones here, and still it won't play nice.我已经在这里将我的代码剥离到几乎裸露的地方,但它仍然不会很好。

The only variable popping out to me is I'm using jQuery's jCanvas, but I doubt that's what the trouble is.突然出现的唯一变量是我正在使用 jQuery 的 jCanvas,但我怀疑这就是问题所在。

Here's the code:这是代码:

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'); 
}

i think your code works.我认为你的代码有效。 This is what i tried http://jsfiddle.net/QXSsE/1/这就是我尝试过的 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');
}

Well, in the link you gave in the comment for the other answer , you clearly have the canvas in the background.好吧,在您在其他答案的评论中给出的链接中,您显然在后台有 canvas。 An event cannot fire if the element is under another element.如果元素在另一个元素下,则无法触发事件。 Your canvas has a z-index of 0 , keeping it below the body .您的 canvas 的z-index0 ,将其保持在body下方。 Using the console, I just changed the z-index and it works perfectly fine.使用控制台,我只是更改了z-index ,它工作得很好。

On a related note, you have probably seen Google's let it snow canvas thing.在相关说明中,您可能已经看到 Google让它下雪canvas 的事情。 If you notice, in the beginning, you can't interact with the snow.如果您注意到,一开始您无法与雪互动。 It has a low z-index .它的z-index很低。 After a while, the z-index is increased, and you can't interact with the text;过了一会z-index变大了,不能和文字交互了; only with the snow.只有雪。

As you can see, this has nothing to do with you using a canvas.如您所见,这与您使用 canvas 无关。 It's just the way events work when elements are positioned over each other.这只是元素相互放置时事件的工作方式。 Simple example illustrating my point.简单的例子说明我的观点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM