2013-06-05 178 views
1

我知道你不能簡單地使用.gif注意:在畫布上,所以我想繪製圖像,然後清除圖像,然後有像半秒然後做下一個圖像等的間隔。帆布.gif注意動畫

現在,這是我做了什麼,但我不知道我有權利,我eant一切都在屏幕上別的原樣移動,甚至在這個時候運行的其他動畫的時間間隔。 (想象一下游戲中的爆炸)

我試過了,但間隔似乎不起作用,它只是一個接一個地繪製所有東西,並清除最後一個,所以你什麼都看不到。

var wide = 70; 
var high = 70; 


ctxExplosion.drawImage(spriteImage,0,1250,wide,high,100,100,wide,high); 
setInterval(500); 
ctxExplosion.clearRect(0,0,canvasWidth,canvasHeight); 

ctxExplosion.drawImage(spriteImage,77,1250,wide,high,100,100,wide,high); 
setInterval(500); 
ctxExplosion.clearRect(0,0,canvasWidth,canvasHeight); 

ctxExplosion.drawImage(spriteImage,150,1250,wide,high,100,100,wide,high); 
setInterval(500); 
ctxExplosion.clearRect(0,0,canvasWidth,canvasHeight); 

ctxExplosion.drawImage(spriteImage,232,1250,wide,high,100,100,wide,high); 
setInterval(500); 
ctxExplosion.clearRect(0,0,canvasWidth,canvasHeight); 

我想它,所以它會顯示類似的動畫,也不想層的清算與其他爆炸當時發生干涉。任何方式在這個?

+0

備註:有一個「遊戲循環」而不是多個setIntervals。更好的是,使用requestFrameAnimation。 – Jarrod

回答

2

這是因爲您沒有正確使用setInterval。 setInterval需要2個參數,一個在指定時間運行的函數和等待時間。

你說什麼有:

  • 畫出我的形象
  • 在半秒什麼都不做
  • 清除我的形象
  • ...等...

舉個例子,你可能會做這樣的事情:

/* Takes an array of offsets, and returns an interval timer representing the current animation*/ 
makeExplosion = function(offsetArray, frameRate) { 
    var currentFrame = 0, interval = null; 

    var animFunc = function() { 
     ctxExplosion.clearRect(0,0,canvasWidth,canvasHeight); 
     ctxExplosion.drawImage(spriteImage,offsetArray[currentFrame],1250,wide,high,100,100,wide,high); 

     currentFrame++; 
     if (interval && (currentFrame > offsetArray.length)) { 
      clearInterval(interval); 
     } 
    } 

    interval = setInterval(animFunc, frameRate); 

    return interval; 
} 

這將運行您的動畫,並返回一個區間對象,以便您可以儘快取消動畫,如果你喜歡。這僅僅是一個例子,你需要傳遞widehigh變量或者對它們做些什麼來確定它們的定義。

我沒有測試的代碼,但它應該是接近的工作。

+0

無法讓你的工作,但設法使用一些,它的工作,我只是不知道它的好代碼? http://pastebin.com/MTFY3Lu7 – Barney

+0

嗯,是的......就像我說過的,你需要做一些有關廣泛和高度變數的事情。這個例子就是這樣。一個例子。 –

+0

如果您正在尋找代碼審查,我至少要從基礎開始(正確縮進,刪除全局變量) –