How to Draw Rectangles and Text with the HTML5 Canvas

5 of 8 in Series: The Essentials of the HTML5 Canvas Tag

A few primitive shapes can be drawn directly onto the graphics context of the canvas element of HTML5. The most common shapes are rectangles and text, which can also have shadows. Here's how you create both.

Drawing rectangles with HTML5 canvas

You can draw three different types of rectangles, as shown in the figure:

  • clearRect(x, y, w, h): Erases a rectangle with the upper-left corner (x,y) and size (w,h). Generally, erasing will draw in the background color.

  • fillRect(x, y, w, h): Draws a box with upper-left corner (x, y) and size (w,h). The rectangle is filled in with the currently defined fillStyle.

  • strokeRect(x, y, w, h): Draws a box with upper-left corner (x, y) and size (w,h). The box is not filled in, but the outline is drawn in the currently-defined strokeStyle and using the current lineWidth.

    image0.jpg

Here's the code that generates the figure:

function draw(){
  var drawing = document.getElementById("drawing");
  var con = drawing.getContext("2d");
  con.fillStyle = "red";
  con.strokeStyle = "green";
  con.lineWidth = "5";
  con.fillRect(10, 10, 180, 80);
  con.strokeRect(10, 100, 180, 80);
} // end draw

Drawing text with HTML5 canvas

The canvas tag has complete support for text. You can add text anywhere on the canvas, using whichever font style and size you want, as shown in this illustration of a canvas with embedded text:

image1.jpg

The first step in drawing text is to pick the font. Canvas fonts are created by assigning a font to the context's font attribute. Fonts are defined like the single-string font assignment in CSS. You can specify all the font characteristics in the same order you do when using the font shortcut: style, variant, weight, size, and family.

When you're ready to display actual text on the screen, use the fillText() method, which accepts three parameters: the text to display and the X and Y position of the left-hand side of the text. The following code produced the results in the figure:

    function draw(){
      var drawing = document.getElementById("drawing");
      var con = drawing.getContext("2d");
      
      //clear background
      con.fillStyle = "white";
      con.fillRect(0,0, 200, 200);
      // draw font in red
      con.fillStyle = "red";
      con.font = "20pt sans-serif";
      con.fillText("Canvas Rocks!", 5, 100);
      con.strokeText("Canvas Rocks!", 5, 130);
    } // end draw
blog comments powered by Disqus
Advertisement
Learning anything is easy with For Dummies eLearning!

Inside Dummies.com