Sprite!
I suggest you place the images in a single image, like a "sprite sheet". This means that you need to pre-assemble the images into one image, load that single image and draw it on the canvas.
That way:
- You only load one image, thus reducing your http requests to the server to one only.
- You draw to the canvas only once. No more loops, no more multiple
drawImage
.
Order in the court!
Loading images are async, thus the need for the event handler. This also means that the images will arrive in any order, and not necessarily in the order you called them down. In your case, the image at index 21 might come earlier than you'd expect, even before all others have loaded.
I suggest you add an onload
to each image and have it check if all images have been loaded before doing anything with them. A simple way to do this is to increment a counter and check if the counter value matches the expected number.
When the count is equal to the expected length, run the code you want to run.
No aftershocks?
If the entire operation was just to load into the canvas the images, it's fine.
However, you aren't loading them for no reason now are you? You are loading them for something. I suggest you wrap this operation in a function, have it accept your url array, and a callback that runs when it finishes loading and rendering all your images on the canvas.
Something like:
loadImagesToCanvas([
//urls
],function(renderedCanvas){
//run when done
});
Math.floor() is slow and long
In some browsers, Math.floor()
is a slow way to trim off the decimal places of a number. Try bitwise OR (|
) instead:
var wholeNumber = decimalNumber | 0;
Unnecessary math
If some consecutive operations use some value resulting from some math operation, cache that value in a variable rather than doing the math again.