Reading Images

How to 3D

Chapter 9: Textures

Reading Images

Before we can apply images to a 3D model, we need to read the images in from disk or a web server. We could do this by passing an image's URL to the browser's asynchronous fetch function. However, fetch does little beyond reading bytes or text. We'd have to parse the file contents ourselves, and image file formats tend to be complex.

A better option is to create a new Image, which is the type that corresponds to an HTML img element. It supports many different image formats. When we set the element's src attribute to the image URL, the browser automatically downloads and parses the image in the background. To pause the main thread until the image is ready, we await the promise returned by the image's decode method, as is done in this utility function:

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

We call readImage from an asynchronous function like this:

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

Reading images should generally be done only once, during initialization. Input and output are much slower than the framerates that users expect.

Though Image can decode many different image file formats, there are currently two primary formats with which you should be familiar:

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

← Detail without TrianglesTexture Setup →