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: an image format that greatly reduces the storage size of photographs. The compression scheme it uses leads to information loss and blurring in areas where the colors change abruptly. JPG doesn't support transparency.
- PNG: an image format that doesn't compress files as efficiently as JPG, but which retains all original color data so that the decompressed image perfectly matches the original. PNG supports transparency. Non-photographic images, such as those made by an artist, are often stored using this format because of its high fidelity.
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.