2013-02-22 32 views
0

我正在開發一個HTML5應用程序,我正在畫布上以一定的速度和每個動畫之間的特定超時畫出一系列圖像。同時發生多個JavaScript超時

能夠多次使用它我已經爲它做了一個功能。

var imgNumber = 0; 
var lastImgNumber = 0; 
var animationDone = true; 

function startUpAnimation(context, imageArray, x, y, timeOut, refreshFreq) { 
    if (lastImgNumber == 0) lastImgNumber = imageArray.length-1; 

    if (animationDone) { 
     animationDone = false; 
     setTimeout(playAnimationSequence, timeOut, refreshFreq); 
    } 
    context.drawImage(imageArray[imgNumber], x, y); 
} 

function playAnimationSequence(interval) { 
    var timer = setInterval(function() { 
     if (imgNumber >= lastImgNumber) { 
      imgNumber = 0; 
      clearInterval(timer); 
      animationDone = true; 
     } else imgNumber++; 
    }, interval); 
} 

現在在我的主代碼中,每次使用正確參數的startUpAnimation它都能正常工作。 但是當我想以不同的間隔和速度同時在屏幕上同時繪製多個動畫時,它不起作用!

startUpAnimation(context, world.mushrooms, canvas.width/3, canvas.height - (canvas.height/5.3), 5000, 300); 
startUpAnimation(context, world.clouds, 100, 200, 3000, 100); 

現在顯示在正確的位置,兩者的動畫,但他們在我的案件5000超時和300間隔動畫無論是在第一個叫的間隔時間和超時,所以。

我該如何解決這個問題,讓他們都獨立玩?我認爲我需要把它變成一堂課或其他東西,但我不知道如何解決這個問題。在某些情況下,我甚至需要使用此功能同時顯示5個動畫。

任何幫助,將不勝感激!

+0

你只得到了一個'imgNumber',一個'lastImgNumber',和一個'兩個動畫animationDone'變量。 – Bergi 2013-02-22 13:45:43

+0

它應該如何動畫?每次調用只繪製一次,間隔只增加一個變量,但除此之外別無其他。 – Bergi 2013-02-22 13:46:46

回答

1

嘗試這樣的事情

  var Class = function() { 
      this.imgNumber = 0; 
      this.lastImgNumber = 0; 
      this.animationDone = true; 

     } 
     Class.prototype.startUpAnimation = function(context, imageArray, x, y, timeOut, refreshFreq) { 
      //  if (lastImgNumber == 0) lastImgNumber = imageArray.length-1; 

      if (this.animationDone) { 
       this.animationDone = false; 
       setTimeout(this.playAnimationSequence, timeOut, refreshFreq, this); 
      } 
      //  context.drawImage(imageArray[imgNumber], x, y); 
     }; 

     Class.prototype.playAnimationSequence = function (interval, object) { 
      var that = object; // to avoid flobal this in below function 
      var timer = setInterval(function() { 
       if (that.imgNumber >= that.lastImgNumber) { 
        that.imgNumber = 0; 
        clearInterval(timer); 
        that.animationDone = true; 
        console.log("xxx"+interval); 
       } else that.imgNumber++; 
      }, interval); 
     }; 


     var d = new Class(); 
     var d1 = new Class(); 
     d.startUpAnimation(null, [], 300, 300, 5000, 50); 

     d1.startUpAnimation(null,[], 100, 200, 3000, 60); 

它應該工作,

+0

您需要繪製圖像。 – 2013-02-22 13:47:22

+0

感謝您的回答,但仍然和以前一樣。 d1.startUpAnimation使用d.startUpAnimation的時間間隔和超時時間,以便它們仍以相同的速率和時間動畫。 – user1732556 2013-02-22 15:14:43

+0

解決了!感謝您的解決方案! – user1732556 2013-02-22 15:19:54

0

就我所見,每次調用startUpAnimation都會立即繪製到畫布上,因爲此執行(您的drawImage(..)調用)未包含在setTimeout或setInterval的回調中。