Tutorial: Drawing Basic Shapes with HTML5 Canvas

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

Example 1. HTML5 canvas tag.

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

Example 2. Rendering a rectangle.
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.