禁用单击EventListener

时间:2015-09-06 09:48:17

标签: javascript html5 event-listener

我正在尝试学习HTML5画布。第一张图片需要七次点击,然后才能看到猫咪GIF吃饼干。最初,我将单击EventListener绑定到图像。在猫gif吃饼干出现后,我无法禁用点击。有什么建议吗?

cat.html

<!DOCTYPE html>
<html>
    <head>
        <title>Cat Animation</title>
    </head>
    <body>
        <div id="canvasDiv"></div>
        <script type="text/javascript" src="cat.js"></script>
        <script type="text/javascript">
            prepareCanvas(document.getElementById("canvasDiv"), 700, 700);
            document.getElementById("canvas").addEventListener("click", function(){console.log("clicked");loadImage("cat");console.log(total);console.log(currentFrame);}, false);
        </script>
    </body>
</html>

cat.js

var canvas;
var context;
var image;
var currentFrame = 0;
var frames = 4;
var width = 350;
var height = 300;
var total = 0
var finalFrame = 0;

function prepareCanvas(canvasDiv, canvasWidth, canvasHeight)
{
    canvas = document.createElement('canvas');
    canvas.setAttribute('width', canvasWidth);
    canvas.setAttribute('height', canvasHeight);
    canvas.setAttribute('id', 'canvas');
    canvasDiv.appendChild(canvas);

    context = canvas.getContext("2d");
    canvas.width = canvas.width;//clears canvas
    loadImage("cat");
};

function loadImage(name)
{
    image = new Image();
    image.src = "images/cat" + currentFrame +".png";
        draw("one");
    if (currentFrame == 3 && total == 1){
        setInterval(finaldraw,110);
    }
};

function draw(params)
{
    image.onload = function(){
        canvas.width = canvas.width;
        context.drawImage(image,0,0);
        currentFrame++;
        if (currentFrame == 4) {
            currentFrame = 0;
            total++;
        };
    }
};

function finaldraw(){
    document.getElementById("canvas").removeEventListener("click",function(){});
    image.src = "images/eatsheet.png";
    image.onload = function(){
        context.drawImage(image,350*finalFrame,0,width,350,0,0,width,350);
        if (finalFrame == frames) {
            finalFrame = 0;
        } else {
            finalFrame = finalFrame + 1;            
        }
    }
};

1 个答案:

答案 0 :(得分:2)

您需要删除添加侦听器时使用的完全相同的函数对象实例。函数表达式求值为新的函数对象,并且与最初注册的函数对象不匹配,即使它具有完全相同的内容(在您的情况下不是......)

解决方案是使用命名函数或赋值函数值的变量,并在add和remove调用中使用相同的标识符。