You are here: Home Dive Into HTML5

Let’s Call It A Draw(ing Surface)

 

Diving In

HTML 5 defines the <canvas> element as “a resolution-dependent bitmap canvas which can be used for rendering graphs, game graphics, or other visual images on the fly.” A canvas is a rectangle in your page where you can use JavaScript to draw anything you want.

Basic <canvas> support
IE8*IE7*Fx3.5Fx3.0Saf4Saf3ChromeOpera
* Internet Explorer support requires the third-party explorercanvas library.

So what does a canvas look like? Nothing, really. A <canvas> element has no content and no border of its own.

 ↜ Invisible canvas

The markup looks like this:

<canvas width="300" height="225"></canvas>

Let’s add a dotted border so we can see what we’re dealing with.

 ↜ Canvas with border

You can have several <canvas> elements on the same page. Each canvas will show up in the DOM, and each canvas maintains its own state. If you give each canvas an id attribute, you can access them just like any other element.

Let’s expand that markup to include an id attribute:

<canvas id="a" width="300" height="225"></canvas>

Now you can easily find that <canvas> element in the DOM.

var a_canvas = document.getElementById("a");

Simple Shapes

IE8*IE7*Fx3.5Fx3.0Saf4Saf3ChromeOpera
* Internet Explorer support requires the third-party explorercanvas library.

Every canvas starts out blank. That’s boring! Let’s draw something.

 ⇜ Click to draw on this canvas

The onclick handler called this function:

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

The 1st line of the function is nothing special; it just finds the <canvas> element in the DOM.

And then there’s this  

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

man drawing in front of a mirror

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 call its getContext() method. You must pass the string "2d" to the getContext() method.

Q: Is there a 3-D canvas?
A: Not yet. Individual vendors have experimented with their own three-dimensional canvas APIs, but none of them have been standardized. The HTML5 specification notes, “A future version of this specification will probably define a 3d context.”

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 methods devoted to drawing rectangles:

Ask Professor Markup

Q: Can I “reset” a canvas?
A: Yes. Setting the width or height of a <canvas> element will erase its contents and reset all the properties of its drawing context to their default values. You don’t even need to change the width; you can simply set it to its current value, like this:

var b_canvas = document.getElementById("b");
b_canvas.width = b_canvas.width;

Getting back to that code sample in the previous example…

Draw a rectangle ⇝ 

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.

Canvas Coordinates

The canvas is a two-dimensional grid. The coordinate (0, 0) is at the upper-left corner of the canvas. Along the X-axis, values increase towards the right edge of the canvas. Along the Y-axis, values increase towards the bottom edge of the canvas.

Canvas coordinates diagram

That coordinate diagram was drawn with a <canvas> element. It comprises

First, we need to define the <canvas> element itself. The <canvas> element defines the width and height, and the id so we can find it later.

<canvas id="c" width="500" height="375"></canvas>

Then we need a script to find the <canvas> element in the DOM and get its drawing context.

var c_canvas = document.getElementById("c");
var context = c_canvas.getContext("2d");

Now we can start drawing lines.

Paths

IE8*IE7*Fx3.5Fx3.0Saf4Saf3ChromeOpera
* Internet Explorer support requires the third-party explorercanvas library.

gerbil sitting on a chair with a quill and ink jar

Imagine you’re drawing a picture in ink. You don’t want to just dive in and start drawing with ink, because you might make a mistake. So you sketch lines and curves with a pencil, and once you’re happy with it, you trace over your sketch in ink.

Each canvas has a path. Defining the path is like drawing with a pencil. You can draw whatever you like, but it won’t be part of the finished product until you pick up the quill and trace over your path in ink.

To draw straight lines in pencil:

  1. moveTo(x, y) moves the pencil to the starting point.
  2. lineTo(x, y) draws a line to an ending point.
  3. Go to step 1.

The more you call moveTo() and lineTo(), the bigger the path gets. These are “pencil” methods — you can call them as often as you like, but you won’t see anything on the canvas until you call one of the “ink” methods.

Let’s draw the off-white grid.

for (var x = 0.5; x < 500; x += 10) {
  context.moveTo(x, 0);
  context.lineTo(x, 375);
}

 ⇜ Draw vertical lines

for (var y = 0.5; y < 375; y += 10) {
  context.moveTo(0, y);
  context.lineTo(500, y);
}

 ⇜ Draw horizontal lines

Those were all “pencil” methods. Nothing has actually been drawn on the canvas yet. We need an “ink” method to make it permanent.

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

stroke() is one of the “ink” methods. It takes the complex path you defined with all those moveTo() and lineTo() calls, and it actually draws it on the canvas. The strokeStyle controls the color of the lines, and this is the result:

Ask Professor Markup

Q: Why did you start x and y at 0.5? Why not 0?
A: Imagine each pixel as a large square. The whole-number coordinates (0, 1, 2…) are the edges of the squares. If you draw a one-unit-wide line between whole-number coordinates, it will overlap opposite sides of the pixel square, and the resulting line will be drawn two pixels wide. To draw a line that is only one pixel wide, you need to shift the coordinates by 0.5 perpendicular to the line's direction.

Now let’s draw the horizontal arrow. All the lines and curves on a path are drawn in the same color (or pattern, or gradient — yes, we’ll get to those soon). We want to draw the arrow in a different color ink — black instead of off-white — so we need to start a new path.

A new path

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);

The vertical arrow looks much the same. Since the vertical arrow is the same color as the horizontal arrow, we do not need to start another new path. The two arrows will be part of the same path.

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);

 ↜ Not a new path

I said these arrows were going to be black, but the strokeStyle is still off-white. (The fillStyle and strokeStyle don’t get reset when you start a new path.) That’s OK, because we’ve just run a series of “pencil” methods. But before we draw it for real, in “ink,” we need to set the strokeStyle to black. Otherwise, these two arrows will be off-white, and we could hardly see them!

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

And this is the result:

Text

IE8*IE7*Fx3.5Fx3.0Saf4Saf3ChromeOpera
··
* Internet Explorer support requires the third-party explorercanvas library.
† Mozilla Firefox 3.0 support requires a compatibility shim.

You can draw lines on a canvas. You can also draw text on a canvas. Unlike text on the surrounding web page, there is no box model. That means none of the familiar CSS layout techniques are available: no floats, no margins, no padding, no word wrapping. (Maybe you think that’s a good thing!) You can set a few font attributes, then you pick a point on the canvas and draw your text there.

The following font attributes are available on the drawing context:

textBaseline is tricky, because text is tricky. Well, English text is not tricky, but you can draw any Unicode character you like on a canvas, and Unicode is tricky. The HTML5 specification explains the different text baselines:

The top of the em square is roughly at the top of the glyphs in a font, the hanging baseline is where some glyphs like are anchored, the middle is half-way between the top of the em square and the bottom of the em square, the alphabetic baseline is where characters like Á, ÿ, f, and Ω are anchored, the ideographic baseline is where glyphs like and are anchored, and the bottom of the em square is roughly at the bottom of the glyphs in a font. The top and bottom of the bounding box can be far from these baselines, due to glyphs extending far outside the em square.

diagram of different values of the textBaseline property

For simple alphabets like English, you can safely stick with top, middle, or bottom for the textBaseline property.

Let’s draw some text! Text drawn inside the canvas inherits the font size and style of the <canvas> element itself, but you can override this by setting the font property on the drawing context.

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

 ↜ Change the font style

The fillText() method draws the actual text.

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

 ⇜ Draw the text

Ask Professor Markup

Q: Can I use relative font sizes to draw text on a canvas?
A: Yes. Like every other HTML element on your page, the <canvas> element itself has a computed font size based on your page’s CSS rules. If you set the context.font property to a relative font size like 1.5em or 150%, your browser multiplies this by the computed font size of the <canvas> element itself.

For the text in the upper-left corner, I want the top of the text to be at y=5. But I’m lazy — I don’t want to measure the height of the text and calculate the baseline. Instead, I can set the textBaseline to top and pass in the upper-left coordinate of the text’s bounding box.

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

For the text in the lower-right corner, I want to be lazy again. I want the bottom-right corner of the text to be at coordinates (492,370) — just a few pixels away from the bottom-right corner of the canvas — but I don’t want to measure the width or height of the text. I can set textAlign to right and textBaseline to bottom, then call fillText() with the bottom-right coordinates of the text’s bounding box.

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

And this is the result:

Oops! We forgot the dots in the corners. I’m going to cheat a little and draw them as rectangles. We’ll see how to draw circles a little later.

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

 ⇜ Draw two “dots”

And that’s all she wrote!

Gradients

FeatureIE8*IE7*Fx3.5Fx3.0Saf4Saf3ChromeOpera
linear gradients
radial gradients··
* Internet Explorer support requires the third-party explorercanvas library.

Earlier in this chapter, you learned how to draw a rectangle filled with a solid color, then a line stroked with a solid color. But shapes and lines aren’t limited to solid colors. You can do all kinds of magic with gradients and patterns.

The markup looks the same as any other canvas.

<canvas id="d" width="300" height="225"></canvas>

First, we need to find the <canvas> element and its drawing context.

var d_canvas = document.getElementById("d");
var context = d_canvas.getContext("2d");

Once we have the drawing context, we can start to define a gradient. A gradient is a smooth transition between two or more colors. The canvas drawing context supports two types of gradients:

  1. createLinearGradient(x0, y0, x1, y1) paints along a line from (x0, y0) to (x1, y1).
  2. createRadialGradient(x0, y0, r0, x1, y1, r1) paints along a cone between two circles. The first three parameters represent the start circle, with origin (x0, y0) and radius r0. The last three parameters represent the end circle, with origin (x1, y1) and radius r1.

Let’s make a linear gradient. Gradients can be any size, but I’ll make this gradient be 300 pixels wide, like the canvas.

Create a gradient object

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

Because the y values (the 2nd and 4th parameters) are both 0, this gradient will shade evenly from left to right.

Once we have a gradient object, we can define the gradient’s colors. A gradient has two or more color stops. Color stops can be anywhere along the gradient. To add a color stop, you need to specify its position along the gradient. Gradient positions can be anywhere between 0 to 1.

Let’s define a gradient that shades from black to white.

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

Defining a gradient doesn’t draw anything on the canvas. It’s just an object tucked away in memory somewhere. To draw a gradient, you set your fillStyle to the gradient and draw a shape, like a rectangle or a line.

Fill style is a gradient

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

And this is the result:

Suppose you want a gradient that shades from top to bottom. When you create the gradient object, keep the x values (1st and 3rd parameters) constant, and make the y values (2nd and 4th parameters) range from 0 to the height of the canvas.

x values are 0, y values vary

var my_gradient = context.createLinearGradient(0, 0, 0, 225);
my_gradient.addColorStop(0, "black");
my_gradient.addColorStop(1, "white");
context.fillStyle = my_gradient;
context.fillRect(0, 0, 300, 225);

And this is the result:

You can also create gradients along a diagonal.

both x and y values vary

var my_gradient = context.createLinearGradient(0, 0, 300, 225);
my_gradient.addColorStop(0, "black");
my_gradient.addColorStop(1, "white");
context.fillStyle = my_gradient;
context.fillRect(0, 0, 300, 225);

And this is the result:

Images

IE8*IE7*Fx3.5Fx3.0Saf4Saf3ChromeOpera
* Internet Explorer support requires the third-party explorercanvas library.

Here is a cat:

sleeping cat

 ⇜ An <img> element

Here is the same cat, drawn on a canvas:

A <canvas> element ⇝ 

The canvas drawing context defines several methods for drawing an image on a canvas.

The HTML5 specification explains the drawImage() parameters:

The source rectangle is the rectangle [within the source image] whose corners are the four points (sx, sy), (sx+sw, sy), (sx+sw, sy+sh), (sx, sy+sh).

The destination rectangle is the rectangle [within the canvas] whose corners are the four points (dx, dy), (dx+dw, dy), (dx+dw, dy+dh), (dx, dy+dh).

diagram of drawImage parameters

To draw an image on a canvas, you need an image. The image can be an existing <img> element, or you can create an Image() object with JavaScript. Either way, you need to ensure that the image is fully loaded before you can draw it on the canvas.

If you’re using an existing <img> element, you can safely draw it on the canvas during the window.onload event.

using an <img> element

<img id="cat" src="images/cat.png" alt="sleeping cat" width="177" height="113">
<canvas id="e" width="177" height="113"></canvas>
<script>
window.onload = function() {
  var canvas = document.getElementById("e");
  var context = canvas.getContext("2d");
  var cat = document.getElementById("cat");
  context.drawImage(cat, 0, 0);
};
</script>

If you’re creating the image object entirely in JavaScript, you can safely draw the image on the canvas during the Image.onload event.

using an Image() object

<canvas id="e" width="177" height="113">
<script>
  var canvas = document.getElementById("e");
  var context = canvas.getContext("2d");
  var cat = new Image();
  cat.src = "images/cat.png";
  cat.onload = function() {
    context.drawImage(cat, 0, 0);
  };
</script>

The optional 3rd and 4th parameters to the drawImage() method control image scaling. This is the same image, scaled to half its width and height and drawn repeatedly at different coordinates within a single canvas.

Here is the script that produces the “multicat” effect:

cat.onload = function() {
  for (var x = 0, y = 0;
       x < 500 && y < 375;
       x += 50, y += 37) {
    context.drawImage(cat, x, y, 88, 56);
  }
};

 ⇜Scale the image

All this effort raises a legitimate question: why would you want to draw an image on a canvas in the first place? What does the extra complexity of image-on-a-canvas buy you over an <img> element and some CSS rules? Even the “multicat” effect could be replicated with 10 overlapping <img> elements.

The simple answer is, for the same reason you might want to draw text on a canvas. The canvas coordinates diagram included text, lines, and shapes; the text-on-a-canvas was just one part of a larger work. A more complex diagram could easily use drawImage() to include icons or graphics.

But wait, there’s more! You can also use canvas properties to transform an image before drawing it.

Transforms

Here is the same cat as before, but upside-down:

…to be continued…

Patterns

FIXME

swirly color pattern

FIXME

FIXME

FIXME

Shadows

Canvas Save As…

Security

FIXME

What About IE?

Microsoft Internet Explorer (up to and including version 8, the current version at time of writing) does not support the canvas API. However, Internet Explorer does support a Microsoft-proprietary technology called VML, which can do many of the same things as the <canvas> element. And thus, excanvas.js was born.

Explorercanvas (excanvas.js) is an open source, Apache-licensed JavaScript library that implements the canvas API in Internet Explorer. To use it, include the following <script> element at the top of your page.

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Dive Into HTML5</title>
  <!--[if IE]>
    <script src="excanvas.js"></script>
<![endif]-->
</head>
<body>
  ...
</body>
</html>

The <!--[if IE]> and <![endif]--> bits are conditional comments. Internet Explorer interprets them like an if statement: “if the current browser is any version of Internet Explorer, then execute this block.” Every other browser will treat the entire block as an HTML comment. The net result is that Internet Explorer will download the excanvas.js script and execute it, but other browsers will ignore the script altogether (not download it, not execute it, not anything). This makes your page load faster in browsers that implement the canvas API natively.

Once you include the excanvas.js in the <head> of your page, you don’t need to do anything else to accomodate Internet Explorer. Just include <canvas> elements in your markup, or create them dynamically with JavaScript. Follow the instructions in this chapter to get the drawing context of a <canvas> element, and you can draw shapes, text, and patterns.

Well… not quite. There are a few limitations:

  1. Patterns must be repeating in both directions.
  2. Gradients can only be linear. Radial gradients are not supported.
  3. Clipping regions are not supported.
  4. Non-uniform scaling does not correctly scale strokes.
  5. It’s slow. This should not come as a raging shock to anyone, since Internet Explorer's JavaScript parser is slower than other browsers to begin with. Once you start drawing complex shapes via a JavaScript library that translates commands to a completely different technology, things are going to be a bit slow. You won’t notice the performance degradation in simple examples like drawing a few lines and transforming an image, but you’ll see it right away once you start doing canvas-based animation and other crazy stuff.

Further Reading

Did You Know?

In association with O’Reilly, Google Press will be publishing this book in a variety of formats, including paper, Kindle, and DRM-free PDF. The printed book will be called “HTML5: Up & Running,” and we hope to release it by next February in the first quarter of 2010 as soon as it’s good and ready, and not a moment sooner. This chapter will be included in the print edition.

If you liked this chapter and want to show your appreciation, you can pre-order “HTML5: Up & Running” with this affiliate link. You’ll get a book, and I’ll get a buck. I do not currently accept direct donations.

Copyright MMIX–MMX O’Reilly Media • written by Mark Pilgrim