Hey guys I recently made a game with the help of my friend using HTML5 canvas with pure javascript a cool idea and a way to learn all the new things buuuut following tutorials I set up the entire game without any onloads or something to load each image object or audio properly so is there a way or some kind of library that can help me with this ?? or do I have to code it for each loaded image?? if so what do you think is the best way to do the preloader ??
HTML5 canvas game pure javascript preloader ?
I would look into javscript Promises
If you use native javascript promises you will limit your browser support. You can use this library if you want wider browser support.
https://github.com/kriskowal/q
At this point you can write a preloader function
If you use native javascript promises you will limit your browser support. You can use this library if you want wider browser support.
https://github.com/kriskowal/q
At this point you can write a preloader function
function preloadImage(url)
{
return new Promise(function(resolve, reject) {
var result = new Image();
result.src = url;
result.onload = resolve;
});
}
Then to preload all images you can use the 'all' feature of promises
function preloadAllImages(imageUrls) {
var loadPromises = [];
for (var i = 0; i < imageUrls.length; ++i) {
loadPromises.push(preloadImage(imageUrls[i]));
}
return Promise.all(loadPromises);
}
Then to wait for everything, you simply do the following
preloadAllImages(allImages).then(function() {
// game code that depends on preload goes here
});
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement