简体   繁体   中英

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.

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/

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. An event cannot fire if the element is under another element. Your canvas has a z-index of 0 , keeping it below the body . Using the console, I just changed the z-index and it works perfectly fine.

On a related note, you have probably seen Google's let it snow canvas thing. If you notice, in the beginning, you can't interact with the snow. It has a low z-index . After a while, the z-index is increased, and you can't interact with the text; only with the snow.

As you can see, this has nothing to do with you using a canvas. It's just the way events work when elements are positioned over each other. Simple example illustrating my point.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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