Skip to content

Instantly share code, notes, and snippets.

@oreillyross
Last active June 1, 2016 10:45
Show Gist options
  • Save oreillyross/848bc362b38c83eeeca779195084615d to your computer and use it in GitHub Desktop.
Save oreillyross/848bc362b38c83eeeca779195084615d to your computer and use it in GitHub Desktop.
A MULTIPLE IMAGE LOADER THAT COUNTS THE LOADED IMAGES AND CALLS A FUNCTION YOU PASS WHEN DONE!
function loadImages(imagesToBeLoaded, drawCallback) {
var imagesLoaded = {};
var loadedImages = 0;
var numberOfImagesToLoad = 0;
// get num of images to load
for(var name in imagesToBeLoaded) {
numberOfImagesToLoad++;
}
for(var name in imagesToBeLoaded) {
imagesLoaded[name] = new Image();
imagesLoaded[name].onload = function() {
if(++loadedImages >= numberOfImagesToLoad) {
drawCallback(imagesLoaded);
} // if
}; // function
imagesLoaded[name].src = imagesToBeLoaded[name];
} // for
} // function
// List of images to load, we used a JavaScript object instead of
// an array, so that named indexes (aka properties)
// can be used -> easier to manipulate
var imagesToLoad = {
flowers:
'http://cdn2.digitalartsonline.co.uk/images/features/1675/intro.jpg',
lion: 'http://farm3.static.flickr.com/2319/2486384418_8c031fec76_o.jpg',
blackAndWhiteLys: 'http://pshero.com/assets/tutorials/0062/final.jpg',
tiledFloor:
'http://4.bp.blogspot.com/_Rqs7w7m37B4/TETj5rD_QmI/AAAAAAAAADk/qRiwoTO-zKk/s1600/symmetry:assymetry+repeatable+pattern.jpg'
};
//Example usage
loadImages(imagesToLoad, function(imagesLoaded) {
patternFlowers = ctx.createPattern(imagesLoaded.flowers, 'repeat');
patternLion = ctx.createPattern(imagesLoaded.lion, 'repeat');
patternBW = ctx.createPattern(imagesLoaded.blackAndWhiteLys, 'repeat');
patternFloor = ctx.createPattern(imagesLoaded.tiledFloor, 'repeat');
drawRectanglesWithPatterns();
});
// Usage
function drawRectanglesWithPatterns() {
ctx.fillStyle=patternFloor;
ctx.fillRect(0,0,200,200);
ctx.fillStyle=patternLion;
ctx.fillRect(200,0,200,200);
ctx.fillStyle=patternFlowers;
ctx.fillRect(0,200,200,200);
ctx.fillStyle=patternBW;
ctx.fillRect(200,200,200,200);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment