In javascript, you can use the setInterval and setTimeout functions to create delays and reduce frame rates.
for example, if you want to make a drawing cycle of about 30 FPS, you might have code that looks like this:
function draw(){ var canvas = document.getElementById('myCanvas');
This will help you control the processing time of the animation. Thus, if you find that your animation is too slow, you can increase the frame rate by changing the denominator of “30” to something like “60” fps or something that really works well for your program.
As for the optimization in addition to setTimeout (), it is very important how you draw the animation. Try loading all of your images before rendering them, this is called "Preload". That is, if you have a bunch of different images for each animated cell, then before you call your drawing function, load all the images into an image array as follows:
var loadedImages = new Array(); loadedImages[0] = new Image(); loadedImages[0].src = "images/animationFrame1.png"; loadedImages[1] = new Image(); loadedImages[1].src = "images/animationFrame2.png"; loadedImages[2] = new Image(); loadedImages[2].src = "images/animationFrame3.png"; loadedImages[3] = new Image(); loadedImages[3].src = "images/animationFrame4.png";
you can even put them in a hash if that makes sense for your application, where instead
loadedImages[0] = new Image(); loadedImages[0].src = "images/animationFrame1.png";
You do it
loadedImages['frame1'] = new Image(); loadedImages['frame1'].src = "images/animationFrame1.png";
After loading all of your images, you refer to them for drawing, calling them like this:
//Using the integer array ctx.drawImage(loadedImages[0], 0, 0); //OR //Using the stringed hash ctx.drawImage(loadedImages['frame1'], 0, 0);
You want to separate the loading process from the rendering process, because loading images is intensive in the process, which will slow down your animations if you load things while rendering.
This does not mean that you can never load anything during rendering, but instead just be a conscience that this will slow down the speed of the animation.
Here is an article about preloading images.
There is another entry here that talks about the constant animation speed in all browsers here
Pay attention to the link sent by the green marked answer
Other things to note should be cleared and the bounding boxes redrawn, as indicated in the article on optimizing HTML 5 canvas. This link has some really good methods to be a conscience when designing canvas animations.
Some frames also work here that may be useful for comparing what you do with what other engines do.
Hope this helps. I am new to javascript (just started writing with it about 2 weeks ago), and so there may be better ways to do something, but this is what I have found so far.