Reading Images

Before you can apply images to a 3D model, you need to read the images in. Previously you used fetch to read in text and JSON files. The text files you had to parse yourself. The JSON files the browser parsed for you.

Images are a bit simpler. Instead of fetch, you create a new Image, which is the type that corresponds to an HTML img element, and set its src to the URL of your image. The browser automatically downloads and parses the image in the background. To pause the main thread until the image is ready, you await the promise returned by the image's decode method.

This utility function does all the work of reading in an image:

async function readImage(url) {
  const image = new Image();
  image.src = url;
  await image.decode();
  return image;
}

You call it from an asynchronous function like this:

const toastImage = await readImage('toast-albedo.png');

The browser can decode many different image file formats. There are two primary formats you should be familiar with:

JPG images are small when compressed, but you will be sending the decompressed images to your graphics card. The decompressed images are not any smaller. The only real advantage of JPG is that your texture assets will take up less space on disk and they will download faster.