Draw a Basic Rectangle with the HTML5 Canvas Tag - dummies

Draw a Basic Rectangle with the HTML5 Canvas Tag

By Andy Harris

To use the canvas tag available in HTML5, build a web page with a canvas element in it. Typically, you provide width, height, and id parameters to indicate how big the cnavas is, like so:

  <canvas id = "drawing"
          width = "200"
          height = "200">
    <p>Your browser does not support the canvas tag...</p>

Inside the canvas tag, you can put any HTML code you want. This code will appear if the browser doesn’t support the canvas tag. Typically, you just put some sort of message letting the user know what she’s missing.

Nothing interesting happens in a canvas without some kind of JavaScript code. Often, you’ll use a function to draw on the screen. Here’s one draw() function, which is called by the body onload event:

  function draw(){
    var canvas = document.getElementById("drawing");
    if (canvas.getContext){
      var con = canvas.getContext('2d');
      con.fillStyle = "#FF0000";
      con.fillRect(10, 10, 50, 50);
    } // end if
  } // end draw

The draw() function illustrates all the main ideas of working with the canvas tag. Here’s how you build a basic drawing:

  1. Create a variable reference to the canvas.

    Use the standard getElementById() mechanism to create a variable referring to the canvas.

  2. Extract the graphics context from the canvas.

    Canvas elements have a graphics context, which is a special object that encapsulates all the drawing methods the canvas can perform. Most browsers support a 2D context now, but 3D contexts are planned.

  3. Set the context’s fillStyle, which indicates how you will color filled-in areas (like rectangles).

    The basic approach is to supply a CSS-style color value.

  4. Create a filled-in rectangle.

    The rectangle shape is pretty easy to build. It expects four parameters: x, y, width, and height. The x and y parameters indicate the position of the rectangle’s top-left corner, and the width and height parameters indicate the size of the rectangle. All measurements are in pixels.