# How to preload images for canvas in JavaScript

<!--
Title: How to preload images for canvas in JavaScrypt
Tags: tutorial, beginners, javascript, canvas, image
-->

# 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.

```javascript
/**
 * @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);
}
```

You can then use it like this:

```javascript
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);
```

---

## End

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

<!-- INCLUDE -->

### Self-promotion

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

- [GitHub](https://redirect.akbal.dev/github)
- [Twitter](https://redirect.akbal.dev/twitter)
- [Dev.to](https://redirect.akbal.dev/dev.to)

<!-- /INCLUDE -->

### 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!**

