DEV Community

Cover image for How to preload images for canvas in JavaScript
Alejandro Akbal
Alejandro Akbal

Posted on • Originally published at

How to preload images for canvas in JavaScript


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 = => {
    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 = [

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


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


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


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!

Top comments (0)