How to preload images for canvas in JavaScript

alejandroakbal

Alejandro Akbal

Posted on January 17, 2023

How to preload images for canvas in JavaScript

Introduction

This past week, I was toying around with the HTML5 canvas element, trying to join two images together.
At first, it seemed fine, but when I tried to reload the website, it was a mess. One image would load, but the other wouldn't.

Investigating, I found out that the images were being loaded asynchronously.
But the JavaScript code was running anyway, without waiting for the images, ending up with a messed up canvas.

That is why I decided to write this tutorial, to help you preload images for canvas in modern JavaScript.


Preload images

With the help of the Promise.all() function, we can devise a solution to preload images.

/**
 * @param {string[]} urls - Array of Image URLs
 * @returns {Promise<HTMLImageElement[]>} - Promise that resolves when all images are loaded, or rejects if any image fails to load
 */
function preloadImages(urls) {
  const promises = urls.map((url) => {
    return new Promise((resolve, reject) => {
      const image = new Image();

      image.src = url;

      image.onload = () => resolve(image);
      image.onerror = () => reject(`Image failed to load: ${url}`);
    });
  });

  return Promise.all(promises);
}
Enter fullscreen mode Exit fullscreen mode

You can then use it like this:

const urls = [
  'https://example.com/image1.png',
  'https://example.com/image2.png',
];

// Important to use `await` here
const images = await preloadImages(urls);

// Can also be destructured
const [image1, image2] = await preloadImages(urls);

// For example:
const canvas = document.getElementById('canvas');
const context = canvas.getContext('2d');

context.drawImage(images[0], 0, 0);
context.drawImage(images[1], 0, 0);
Enter fullscreen mode Exit fullscreen mode

End

That was it.
It's a small one-time setup on your project, that works like a charm.

Self-promotion

If you have found this useful, then you should follow me, I will be posting more interesting content! 🥰

Conclusion

Congratulations, today you have learned how to preload images for canvas in modern JavaScript. Without needing to complicate your code or use libraries.

Let me know if the tutorial was useful to you in the comments!

💖 💪 🙅 🚩
alejandroakbal
Alejandro Akbal

Posted on January 17, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related