Canvas

The canvas object was introduced in HTML5 as a way of drawing on the screen. Throughout the course we will use the canvas both to give practice in using objects and to provide variety in the exercises and examples presented.

Setting up the canvas

Using the canvas requires the inclusion of a canvas element (tag nameThe characters used in a tag for a particular element. canvas) in the HTML document, such as:

<canvas id="thecanvas" width="500" height="300"></canvas>

The width and height of the canvas element should be set as attributesExtra information added to an element., not in a style sheetStyling inside or outside an HTML element.. The problem is that the CSS height and width propertiesAn aspect of an element that can be styled. are not the same as the canvas height and width. If no dimensions are specified, the default height will be 150 and the default width will be 300. The IDAn attribute used to refer to a single element. is used for reference by the JavaScript program. I've used the word canvas in the name thecanvas, but this is not required: any name can be used.

A JavaScript program that uses the canvas will contain the two lines listed below. The first line sets the variable myCanvas to access the canvas element in the HTML document. You will learn its meaning in the upcoming lesson on the Document Object Model; for the moment all you need to know is that the input should be the value of the ID used in the HTML document (in this case, thecanvas). Again, I've chosen to use the word canvas in the variable name myCanvas, but this is not required, as any name can be used.

The second line retrieves the object context using the method .getContext("2d"). In all the examples in the course, we will use the method in this way to obtain a 2d drawing context.

var myCanvas = document.getElementById("thecanvas");
var context = myCanvas.getContext("2d");

Using the canvas

In the rest of our discussion, we will assume that we've retrieved an object context. The following are all propertiesA slot for one of the values bundled in an object. of the object.

Name Meaning
lineWidth the number of pixels wide a line should be
strokeStyle a string giving the colour of a line
lineCap a string indicating how the ends of the line can be shaped
fillStyle a string giving the colour of a closed path
font the size and name of the font

Values for lineCap include the default butt as well as round and square. A font size and name can be specified as "20px Helvetica".

For example, the following assignments could be made to the context properties in preparation for drawing:

context.lineWidth = 20;
context.strokeStyle = "blue";
context.lineCap = "round";
context.font = "20px Times";