A Brief Foray Into the Canvas Element: How to Draw Basic Shapes

by Joe Laudato

The canvas element is a mixture of HTML5 and javascript, and– on a basic level– may be used to quickly and easily conjure basic two dimensional forms and shapes. Instead of clicking and dragging forms into creation with a mouse, however, typing HTML5 code will be the means of sketching canvas shapes.

The first step in conjuring images out of text is setting up a rudimentary canvas template. This consists of both a <canvas> and <script> tag:

<canvas id="exampleCanvas" width="500" height="500">
     This text between the canvas tags is displayed when a browser does not support canvas.

var canvas = document.getElementById('exampleCanvas');
var context = canvas.getContext('2d');

<!--Sketching content-->

This basic canvas template accomplishes several important goals: it defines “exampleCanvas” as a canvas element, it defines the width and height of the canvas in pixels, and presents a browser incompatibility¬†message should the canvas tag fail to work.

Sketching Via Keyboard

Think of the canvas grid as the bottom right-hand quadrant of the Cartesian coordinate plane. At the top left-hand corner of the canvas grid lies the origin, from which a basic canvas line will originate. For example, this code if placed within the <script> and </script> tags will produce a singular vertical line which extends 100 pixels downwards from the origin:



Upon modifying (0,100) to (40, 100) in the above code, the line’s origin remains at the upper left-hand corner, but the line’s target shifts 40 pixels to the right.


Manipulating the context.lineTo values again in the above code also produces interesting results. While context.moveTo modifies the line’s target, context.lineTo modifies the line’s origin. Setting (25, 0) will shift the origin 25 pixels to the right, and setting (0, 25) will shift the origin 25 pixels downward.

Once you’ve set up one line of “context.lineTo(30, 40)” the origin is redefined as the line’s target [which is in this case (30,40)]. You can define the origin initially with context.moveTo and then set up a chain of context.lineTo’s in order to make a shape. A triangle goes like this:

 context.moveTo(100, 0);
 context.lineTo(150, 100);
 context.lineTo(50, 100);
 context.lineTo(100, 0);


Fear not; drawing objects is not always so tedious in canvas. Making a rectangle uses a much simpler code:

 context.fillStyle = 'blue';
 context.globalAlpha = .6;
 context.rect(100, 75, 100,100);


(In this rectangle I’ve also modified its transparency to 60% using context.globalAlpha and it’s fill colour using context.fillStyle. )

A final, easily drawn shape in canvas is a circle, encoded like so:

 context.globalAlpha = .5;
 context.fillStyle = 'orange';
 context.arc(200,175,50,0,2 * Math.PI, 0);


~ by jtl29 on February 5, 2013.

%d bloggers like this: