Simple Shapes

IE[a]

Firefox

Safari

Chrome

Opera

iPhone

Android

7.0+

3.0+

3.0+

3.0+

10.0+

1.0+

1.0+

[a] Internet Explorer support requires the third-party explorercanvas library.

Every canvas starts out blank. That’s boring! Let’s draw something. You can use the onclick handler to call a function that draws a rectangle (see http://diveintohtml5.org/canvas.html for an interactive example):

function draw_b() {
  var b_canvas = document.getElementById("b");
  var b_context = b_canvas.getContext("2d");
  b_context.fillRect(50, 25, 150, 100);
}

The first line of the function is nothing special; it just finds the <canvas> element in the DOM. The second line is where it gets more interesting. Every canvas has a drawing context, which is where all the fun stuff happens. Once you’ve found a <canvas> element in the DOM (by using document.getElementById() or any other method you like), you can call its getContext() method. You must pass the string "2d" to the getContext() method:

function draw_b() {
  var b_canvas = document.getElementById("b");
  var b_context = b_canvas.getContext("2d");
  b_context.fillRect(50, 25, 150, 100);
}

So, you have a <canvas> element, and you have its drawing context. The drawing context is where all the drawing methods and properties are defined. There’s a whole group of properties and methods devoted to drawing rectangles:

  • The fillStyle property can be a CSS color, a pattern, or a gradient. (More on gradients shortly.) The default fillStyle is solid black, but you can set it to whatever you like. Each drawing context remembers its own properties as long as the page is open, unless you do something to reset it.

  • fillRect(x, y, width, height) draws a rectangle filled with the current fill style.

  • The strokeStyle property is like fillStyle—it can be a CSS color, a pattern, or a gradient.

  • strokeRect(x, y, width, height) draws a rectangle with the current stroke style. strokeRect doesn’t fill in the middle; it just draws the edges.

  • clearRect(x, y, width, height) clears the pixels in the specified rectangle.

Getting back to that code in the previous example:

var b_canvas = document.getElementById("b");   
var b_context = b_canvas.getContext("2d");
b_context.fillRect(50, 25, 150, 100);

Calling the fillRect() method draws the rectangle and fills it with the current fill style, which is black until you change it. The rectangle is bounded by its upper-left corner (50, 25), its width (150), and its height (100). To get a better picture of how that works, let’s look at the canvas coordinate system.

Get HTML5: Up and Running now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.