Sidequest

Setting up the Canvas

Obtain the Canvas Context2d

Before we can draw anything, we need to get the canvas setup. Query for the canvas element, then obtain the 2d rendering context.

Add the following to main.ts:

1
const canvas = document.querySelector("canvas");
2
if (canvas == null) {
3
throw new Error("Could not find canvas element");
4
}

Next, the getContext() method is used to obtain the 2d rendering context.

1
const canvas = document.querySelector("canvas");
2
if (canvas == null) {
3
throw new Error("Could not find canvas element");
4
}
5
+
const context = canvas.getContext("2d");
+
if (context == null) {
+
throw new Error("Could not obtain 2d context");
+
}

Great, but what is the 2d context?

The canvas element provides the surface we draw to, but it does not provide the API we need to make that happen. This is the job of the CanvasRenderingContext2D object, which we can obtain by calling the getContext method on the canvas element. There are other contexts as well, such as webgl for 3d.

Width and Height

Currently the canvas is set to its default resolution (typically 300x150), let's change that. We’re going to target a resolution of 352 x 576 pixels. Before we update the canvas, let's create a new file: src/config.ts, to track some of our configuration over time. This will help avoid some magic numbers in our code.

1
export const config = {
2
/**
3
* In pixels
4
*/
5
gameWidth: 352,
6
7
/**
8
* In pixels
9
*/
10
gameHeight: 576,
11
};
12
13
export type Config = typeof config;

We'll use config to set the size of the canvas element.

+
import { config } from "#/config";
2
3
// ...
4
+
canvas.width = config.gameWidth;
+
canvas.height = config.gameHeight;
7
8
const context = canvas.getContext("2d");

Image Smoothing

After we obtain the 2d context, we're going to disable image smoothing as well. We're after a pixel art look, so we don't want any sort of smoothing to apply. This should only apply when scaling images up, but we'll disable it to be explicit.

1
const context = canvas.getContext("2d");
2
if (context == null) {
3
throw new Error("Could not obtain 2d context");
4
}
5
+
context.imageSmoothingEnabled = false;

At this point the canvas is in a good state to draw to in the next chapter.