2013-02-22 31 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的回调中。