Jump to content
  • Advertisement
Sign in to follow this  
CNBlack

HTML5 canvas game pure javascript preloader ?

This topic is 978 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
Advertisement
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!