1

I know you cannot simply use .gif on canvas so I guess drawing the image then clearing the image then having an interval of like half a second then doing the next image and so on.

Now this is what I've done, but I'm not sure I have got the interval right as I eant everything else on screen to move as is, even other animations running at this time. (think explosions in a game)

I tried this, but the intervals dont seem to work, it just draws everything one after another and clears the final one so you dont see anything.

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);

I want it so it will show like an animation, but also don't want the clearing of the layer to interfere with other explosions happening at the time. Any way around this?

4

1 回答 1

2

这是因为您没有正确使用 setInterval。setInterval 接受 2 个参数、一个在指定时间运行的函数和等待时间。

你说的是:

  • 画出我的形象
  • 半秒内什么都不做
  • 清除我的图像
  • ... ETC ...

例如,您可能会执行以下操作:

/* 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;
}

这将运行您的动画,并返回一个间隔对象,以便您可以根据需要尽快取消动画。这只是一个示例,您需要传入wideand highvars 或对它们做一些事情以确保它们被定义。

我还没有测试代码,但它应该接近工作。

于 2013-06-05T15:09:55.020 回答