Created
December 24, 2012 11:05
-
-
Save rememberlenny/4368854 to your computer and use it in GitHub Desktop.
Image loader function that takes in a hash of image sources, creates an hash of images, and then calls a user defined function whenever all of the images have loaded. From http://www.html5canvastutorials.com/tutorials/html5-canvas-image-loader/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script> | |
function loadImages(sources, callback) { | |
var images = {}; | |
var loadedImages = 0; | |
var numImages = 0; | |
// get num of sources | |
for(var src in sources) { | |
numImages++; | |
} | |
for(var src in sources) { | |
images[src] = new Image(); | |
images[src].onload = function() { | |
if(++loadedImages >= numImages) { | |
callback(images); | |
} | |
}; | |
images[src].src = sources[src]; | |
} | |
} | |
var canvas = document.getElementById('myCanvas'); | |
var context = canvas.getContext('2d'); | |
var sources = { | |
darthVader: 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg', | |
yoda: 'http://www.html5canvastutorials.com/demos/assets/yoda.jpg' | |
}; | |
loadImages(sources, function(images) { | |
context.drawImage(images.darthVader, 100, 30, 200, 137); | |
context.drawImage(images.yoda, 350, 55, 93, 104); | |
}); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment