2015-09-06 107 views
1

我努力學習HTML5的畫布。第一張圖片需要點擊七次,然後纔會出現貓咪圖片。最初,我將一個Click 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;    
     } 
    } 
}; 

回答

2

您需要刪除,當你添加偵聽您使用完全相同的函數對象實例。函數表達式計算爲一個新的函數對象,以及不符合最初註冊的人,即使它有完全相同的內容(而你的情況是不是... ...)

解決的辦法是有一個命名函數或賦值給它的函數值的變量,並在add和remove調用中使用相同的標識符。

+0

你有什麼樣的代碼?我不能真的想象,因爲我還是蠻新的節目:)非常感謝你能不能幫 – ikanyu

+0

看[這裏](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/ removeEventListener) – Amit