HTML5 Canvas is a bitmap drawing surface controlled entirely from JavaScript. The four exercises below cover the foundation: getting a 2D context, drawing and clearing rectangles, constructing a grid with labels, making a linear gradient, and placing an image on the canvas.

Starting with rectangles, clearing, and resetting

A rectangle drawn and partly cleared on a canvas

A canvas starts with an empty drawing context. After selecting the <canvas> element, call getContext('2d') to obtain the tools for drawing. fillRect draws a filled rectangle; coordinates and size are passed in that order. clearRect removes a rectangular area from what has already been painted. The example also schedules a reset: assigning the canvas width to itself after three seconds clears the surface and returns it to a blank state.

<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <style type="text/css" media="all">
    .pos {
      text-align: center;
    }
    .canvas {
      border: 1px solid #ccc;
    }
  </style>

  <title>html5 canvas</title>
</head>
<body>
  <div class="pos">
    <canvas id="a1" class="canvas" width="300" height="200"></canvas>
  </div>

</body>
  <script type="text/javascript" charset="utf-8">
    var a_canvas = document.getElementById("a1");
    var a_context = a_canvas.getContext("2d");
    a_context.fillRect(10, 20, 30, 40);
    a_context.clearRect(10, 20, 10, 10);
    setTimeout(function () {
      a_canvas.width = a_canvas.width;
    }, 3000);
  </script>
</html>

In this snippet the fill is placed at x=10, y=20, 30 pixels wide and 40 pixels tall. The clear operation removes only a 10 by 10 patch at the same starting point. The width assignment is a simple way to reset the bitmap.

Building a grid coordinate system

A grid with x and y axes and corner labels

A coordinate grid can be drawn with paths. moveTo positions the pen without drawing; lineTo adds a line segment. Repeating those calls creates all the vertical and horizontal lines. Setting strokeStyle before calling stroke controls the line color. The first pass uses a light gray for the grid, then a second path draws black axis lines and arrowheads. Text labels for the axes and corner coordinates are added with fillText; textBaseline and textAlign control how the text is anchored relative to the coordinates.

<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <style type="text/css" media="all">
    .pos {
      text-align: center;
    }
    .canvas {
      border: 1px solid #ccc;
    }
  </style>

  <title>html5 canvas</title>
</head>
<body>
  <div class="pos">
    <canvas id="a1" class="canvas" width="500" height="375"></canvas>
  </div>

</body>
  <script type="text/javascript" charset="utf-8">
    var a_canvas = document.getElementById("a1");
    var context = a_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 = "#eee";
    context.stroke();

    context.beginPath();
    context.moveTo(0, 40);
    context.lineTo(240, 40);
    context.moveTo(260, 40);
    context.lineTo(500, 40);
    context.moveTo(495, 35);
    context.lineTo(500, 40);
    context.lineTo(495, 45);

    context.moveTo(60, 0);
    context.lineTo(60, 153);
    context.moveTo(60, 173);
    context.lineTo(60, 375);
    context.moveTo(65, 370);
    context.lineTo(60, 375);
    context.lineTo(55, 370);

    context.strokeStyle = "#000";
    context.stroke();

    context.font = "bold 12px sans-serif";
    context.fillText("x", 248, 43);
    context.fillText("y", 58, 165);

    context.textBaseline = "top";
    context.fillText("( 0, 0 )", 8, 5);

    context.textAlign = "right";
    context.textBaseline = "bottom";
    context.fillText("( 500, 375 )", 492, 370);

    context.fillRect(0, 0, 3, 3);
    context.fillRect(497, 372, 3, 3);


  </script>
</html>

The loops step by 10 pixels and start at 0.5 so the one-pixel lines fall cleanly on the canvas. The axes are split around their labels to leave space for the x and y characters. Small 3 by 3 rectangles mark the origin and the opposite corner.

Creating a color gradient

A black-to-white linear gradient across a canvas

Linear gradients are created between two points and then used as a fill style. createLinearGradient defines the start and end of the color transition. addColorStop places colors along that line, with values from 0 to 1. Once the gradient is assigned to fillStyle, any filled shape uses it.

<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <style type="text/css" media="all">
    .pos {
      text-align: center;
    }
    .canvas {
      border: 1px solid #ccc;
    }
  </style>

  <title>html5 canvas</title>
</head>
<body>
  <div class="pos">
    <canvas id="a1" class="canvas" width="300" height="200"></canvas>
  </div>



</body>
  <script type="text/javascript" charset="utf-8">
    var a_canvas = document.getElementById("a1");
    var context = a_canvas.getContext("2d");

    var my_gradient = context.createLinearGradient(0, 0, 300, 200);

    my_gradient.addColorStop(0, "black");
    my_gradient.addColorStop(1, "white");

    context.fillStyle = my_gradient;
    context.fillRect(0, 0, 300, 200);


  </script>
</html>

Here the gradient runs diagonally from the top-left to the bottom-right of a 300 by 200 canvas, transitioning from black to white. The full canvas is then filled with fillRect.

Drawing an image onto the canvas

An image drawn on a canvas animation

Canvas can also draw an existing image element. The image must already be available in the document; after selecting it, drawImage places it on the canvas with x and y coordinates plus optional width and height. The example clears the canvas each second and draws the image at a random position, creating a simple animation.

<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <style type="text/css" media="all">
    .pos {
      text-align: center;
    }
    .canvas {
      border: 1px solid #ccc;
    }
  </style>

  <title>html5 canvas</title>
</head>
<body>
  <div class="pos">
    <img id="img" src="index.jpg" alt="index" width="50" height="50">
    <canvas id="a1" class="canvas" width="300" height="200"></canvas>
  </div>



</body>
  <script type="text/javascript" charset="utf-8">
    var a_canvas = document.getElementById("a1");
    var context = a_canvas.getContext("2d");
    var img = document.getElementById("img");

    setInterval(function () {
      a_canvas.width = a_canvas.width;
      var x = Math.floor((Math.random() * 240));
      var y = Math.floor((Math.random() * 140));
      context.drawImage(img, x, y, 60, 60);
    }, 1000);

  </script>
</html>

The random x and y values are limited so the 60 by 60 image stays inside the 300 by 200 canvas. Resetting the width each time clears the previous frame. This is a small effect, but it shows how canvas can be combined with timers and randomization.

Canvas is a flexible surface for expressing ideas visually. Starting with primitives, paths, gradients, and images provides a base for more useful and playful experiments.