(click anywhere to close)

[Canvas] The canvas Element

category: Website | course: Canvas | difficulty:
1. Timing
2. Coordinate System

From an HTML perspective, creating a canvas is nothing special. It's just a regular tag with no extraordinary attributes or syntax. To create a canvas, use:

<canvas id=”myID” width=”width” height=”height”> fallback text </canvas>

The fallback text is displayed only if a user’s browser doesn’t support this element.

Unlike the rest of HTML, you shouldn’t use CSS to set the width and height of the canvas. The canvas defaults to a size of 300px (width) by 150px (height), and if you set a width or height with CSS, it simply stretches or shrinks the original canvas image to be this size. Sometimes you want that, but more often than not you don’t. If you want your canvas to be a specific size, set the width and height attributes on the canvas element itself.

And last but not least, we need to set an id if we want to be able to access the canvas element with JavaScript. Of course, there are other ways to select elements, but this is by far the easiest.


One of the common issues with JavaScript is that you need to wait for elements to finish loading before you can access them. Therefore, any code that wants to manipulate the canvas needs to be executed at the right time. There are two common ways to do so: by placing your code after the canvas element within the body of the page, or by placing it inside a function that is called after the page has been loaded.

Accessing the canvas can be done in the same way you’d access any other element, with getElementById(), but that is not enough if we want to draw something on it. We need to access the part of the element that is responsible for drawing, which is done with getContext(‘2d’). Any time I refer to the context in this course, I mean this 2D context of the canvas. Any and every canvas method should be applied to its context, and not the element itself.

<canvas id="myCanvas" width="600" height="300">
	<p>Sorry, your browser doesn't support the CANVAS element.</p>
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');

//Perform canvas operations with the context stored in the ctx variable
//For example, creating a rectangle!

I will leave out this important bit of JavaScript in the examples from now on, but never forget to include it yourself!

Coordinate System

Before we continue our journey into the world of canvas, I need to clear up one thing. The coordinate system used is not like in traditional mathematics (Cartesian coordinates).

In the traditional system, moving upwards from the origin increases values on the y-axis. In the canvas system, the origin is at the top left corner, and moving downwards increases values on the y-axis.

Do you like my tutorials?
To keep this site running, donate some motivational food!
Chocolate Milk