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
:
Next, the getContext()
method is used to obtain the 2d rendering 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.
We'll use config
to set the size of the canvas element.
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.
At this point the canvas is in a good state to draw to in the next chapter.