Sign in to follow this  

HTML5 canvas game pure javascript preloader ?

This topic is 670 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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 ??

Share this post


Link to post
Share on other sites
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
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
});

Share this post


Link to post
Share on other sites

This topic is 670 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this