A blank canvas

For an artist to create a beautiful painting, he starts with a blank canvas. The HTML5 canvas element is a rendering platform that allows you to draw whatever you want on it by using JavaScript. Create a new file called game.html and add the canvas element to the body of the document. Let's give the canvas a width and height of 500 pixels, and assign it an id so we can easily select it in our JavaScript code. Speaking of JavaScript, let's go ahead and create a new file called game.js in the same folder as game.html. Then we can add a reference to the file by using a <script> tag.

		<title>Snake game</title>
		<canvas id="canvas" width="500" height="500"></canvas>
		<script src="game.js"></script>

We've just laid the groundwork for our game. This is actually the first and last time you will write HTML in this tutorial - everything else will be written in JavaScript! If you open game.html in your favorite browser, you won't see anything on the screen yet. Let's change that by writing some code to draw something on the canvas! Open up your game.js file and get the canvas element. I chose to get the canvas element by it's id that we set earlier.

let canvas = document.getElementById("canvas");

Now that we have a reference to the canvas element, let's get the width and height of the canvas. The canvas stores width and height in attributes as strings - width="500" - for example. When we get the width and height attributes, let's convert the strings into numbers so that we can do math with the canvas width and height later on.

const width = Number(canvas.width);
const height = Number(canvas.height);
We declare these variables as constants because their value should never change.

The next thing we want to do is get the canvas' 2d context and store it in a variable. The canvas context is what we will use to actually draw on the canvas. Read more about CanvasRenderingContext2D on MDN.

That was my first link to the MDN documentation!

For the rest of this course, I am not going to write a sentence saying "to learn more, click HERE" each time I want to provide a reference. All of the links you see will be to documentation. Reading the docs will help you understand what's going on in the code if you are new to programming in JavaScript.

let ctx = canvas.getContext("2d");

Now that we have the context to draw on the canvas, let's fill it with a color! We will use the fillRect function to draw a rectangle that takes up the entire canvas. By default, the origin of the canvas sets x: 0, y: 0 to be the top-left corner of the canvas. Therefore, we use the canvas' width and height to determine the width and height of the rectangle we want to draw on it.

ctx.fillStyle = "blue";
// fillRect(x, y, w, h)
ctx.fillRect(0, 0, width, height);

Blue Rectangle


We painted the canvas! Now let's take a break from JavaScript art school and talk about the most foundational game logic...