Sidequest

Loading the Sprite Sheet

Let's start by loading our sprite sheet image so we can draw the background.

Image Loader

It would be convenient to use await to load an image. We'll create a promisifed wrapper around the image loading process to accomplish this.

Create a new file:

1
/**
2
* Loads an image
3
* @param path image URL
4
*/
5
export const loadImage = (path: string): Promise<HTMLImageElement> =>
6
new Promise((resolve, reject) => {
7
const image = new Image();
8
image.onload = () => resolve(image);
9
image.onerror = (err) => reject(err);
10
11
// Kick off the loading process
12
image.src = path;
13
});

Now let's modify main.ts to load the sprite sheet:

+
import spriteSheetUrl from "#/assets/image/spritesheet.png";
2
import { config } from "#/config";
+
import { loadImage } from "#/lib/asset-loader";
4
+
const spriteSheet = await loadImage(spriteSheetUrl);
6
7
const canvas = document.querySelector("canvas");
8
if (canvas === null) {
9
throw new Error("Could not find canvas element");
10
}

With the sprite sheet loaded, we'll draw the background next.