Reputation: 31
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?
Upvotes: 1
Views: 431
Reputation: 10804
This is because you are not using setInterval properly. setInterval takes 2 arguments, a function to run at the specified time, and the wait time.
What you're saying there is:
As an example, you might do something like this:
/* 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;
}
This will run your animation, and return you an interval object so you can cancel the animation sooner if you like. This is just an example, you'll need to pass in the wide
and high
vars or do something with them to make sure they are defined.
I haven't tested the code, but it should be close to working.
Upvotes: 2