向Canvas添加事件侦听器

时间:2011-12-22 08:27:48

标签: javascript jquery html5 javascript-events

这应该不是问题,但我无法弄清楚为什么我的事件监听器没有触发。我已经将我的代码剥离到这里附近的裸骨,但它仍然不会很好玩。

对我来说唯一的变量是我正在使用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'); 
}

感谢您花时间看我愚蠢的难题

2 个答案:

答案 0 :(得分: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');
}

答案 1 :(得分:1)

嗯,在the link you gave in the comment for the other answer中,你明显在背景中有画布。如果元素位于另一个元素下,则无法触发事件。您的画布的z-index0,保持在body以下。使用控制台,我刚刚更改了z-index,它完全正常。

在相关的说明中,您可能已经看过Google的let it snow画布。如果您注意到,在开始时,您无法与雪相互作用。它有一个低z-index。过了一会儿,z-index会增加,你无法与文字互动;只有下雪了。

如您所见,这与您使用画布无关。这就是当元素相互定位时事件的工作方式。 Simple example illustrating my point.