Tutorial: Basic Shapes with HTML5 Canvas

HTML5 canvas elements may be used to draw graphics programatically via JavaScript.

Example 1. HTML5 canvas tag.

1
<canvas id="c" width="400" height="300" style="border: 1px dotted green;"></canvas>

Using the canvas tag’s id attribute, we may first retrieve the DOM element representing the canvas then retrieve the DOM canvas element’s drawing context. With the drawing context handy, rendering simple shapes are no problem. There are a number of methods that facilitate the rendering of rectangles:

Listing 1. Common methods for rectangle rendering

  • fillStyle – Context property that may be a CSS color, gradient, or pattern. Defaults to black;
  • fillRect(x, y, width, height) – Context method to draw a rectangle with its top left corner at x,y and bottom right corner at x+width, y+height.
  • strokeStyle – Context property, similar to fillStyle, to set stroke style (think border);
  • strokeRect(x, y, width, height) – Draws rectangle with current strokeStyle and no fill;
  • clearRect(x, y, width, height) – Clears the pixels within the specified rectangle.

Example 2. Rendering a rectangle.

1
2
3
4
5
6
var canvas = document.getElementById('c');
var context = canvas.getContext("2d");
       
context.fillRect(50, 50, 200, 200);
context.strokeStyle = "red";
context.strokeRect(40, 40, 220, 220);

Here is the result:

Canvas coordinates

The canvas element is a two dimensional grid. The coordinate system begins at the upper left corner of the element (0, 0). Along the x axis, coordinate values increase from left to right. Along the y-axis, coordinate values increase toward the bottom of the canvas. Let’s draw a grid to illustrate the grid concept.

Example 3. Drawing a grid.

1
<canvas id="c-grid" width="500" height="375"></canvas>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
var canvas = document.getElementById('c-grid');
var context = canvas.getContext("2d");

for(var x = 0.5; x < 500; x += 10) {
  context.moveTo(x, 0);
  context.lineTo(x, 375);
}
 
for(var y = 0.5; y < 375; y += 10) {
  context.moveTo(0, y);
  context.lineTo(500, y);
}
context.strokeStyle = "#000";
context.stroke();

Here is the result:

To draw the grid above, some new methods and a new property were used:

  • moveTo(x, y) – Places canvas ‘pencil’ at specified coordinate
  • lineTo(x, y) – Draws a line from the moveTo() coordinate to the specified coordinate (x,y)
  • stroke() – Inks or actually draws the path defined by moveTo() and lineTo()
  • strokeStyle – This property is used to set or get the color, gradient, or pattern used for strokes

Reference:
Pilgrim, M. (2010). HTML5: up and running. Beijing: O’Reilly.