The cool thing with the new open-source canvas element is that not only can you create dynamic images on the fly, but the users' actions can create new images in real time as well—all without requiring a plugin. Sounds great, right? In many ways it is, but it also leaves our friends using assistive technologies out in the cold.

What will happen if you're using a browser that doesn't support the new canvas element? Pretty much nothing. The browser just won't display it. That's why you'll need to be especially careful with this technology and not place anything inside the new canvas element on which your site or application absolutely depends. You must also consider fallback content.

Browsers that support canvas include:

Before proceeding with developing with the new canvas element, make sure you have a good foundation of skills with HTML and JavaScript. Being comfortable with object-oriented programming sure wouldn't hurt either.

How it works...

Of course, we can use whatever height and width dimensions we need, but that simple set of tags is what we need to start.

You're probably thinking we could use CSS to control the height and width, but resist that temptation. Because the new canvas element contains a 2d rendering context, that approach can cause unpredictable behavior.

He's smart

"Let me make one thing completely clear: When you use canvas, you're not drawing on the canvas element itself. Instead, you're actually drawing on the 2d rendering context, which you're accessing through the canvas element via the JavaScript API." – Rob Hawkes

What am I sayin'?

Apple first introduced the new canvas element for the OSX Dashboard years ago. It was later implemented in web browsers Safari and then Chrome, with other browsers following suit. Since then it's become an official part of the HTML5 specification.

What's next for <canvas>?

Right now, we're barely scratching the surface of what the new canvas element can do. Now and in the future we'll use it to create animations, charts, diagrams, drawing apps, graphs, and user interfaces. What will you dream up?

See also

Developer Martin Angelov penned a great how-to guide titled, "An HTML5 Slideshow w/Canvas & jQuery" for Tutorial Zine at: http://tutorialzine.com/2010/09/html5-canvas-slideshow-jquery. In it, Martin demonstrates how to combine the new canvas element with jQuery, the most popular JavaScript framework, to create an intensely interactive image slideshow.

Understanding the 2d rendering context

It's important to understand that the new canvas element is really a "surface" on which to draw bitmapped images in the browser.

There's more...

This example may not seem overwhelming at first, but when you remember that we've created an image with hardly any HTML and no CSS whatsoever, the new canvas element starts to look pretty impressive.

Any way you want it

Note that while we used color names ("white" and "red") we could also use hexadecimal values or RGB or even HSL! Use whatever makes the most sense for you and your interactive project.

Similar to tables?

Think of the color and size specifications for this example almost as the old-school tables we used to build back in the day for layout. While certainly not the same, there are definitely similarities to that technique in this case.

Be a square first

Mastering rectangles is the first canvas technique that's important to have under your belt after the ability to set up the element itself. Understanding the basics of this approach will help you grasp the fundamentals of the next few recipes.

Drawing borders for images using canvas

Let's take a closer look at the super simple method of drawing borders around images using the new canvas element.

How to do it...

First, we'll start with our basic canvas code and add one new line to draw a border:

Creating interactive visualizations

The team at Carbon Five had a daunting task: To create a physical diagram of their skills and interests. They may have started with a wall in their office, but quickly realized the new abilities the new canvas element brings to the table would allow interactivity and the ability to draw conclusions based on it. Here's how they did it at: http://carbonfive.github.com/html5-playground/interest-map/interest-map.html.

Here's a detailed look at some of what they're doing with JavaScript and the new canvas element. They start with some variables like the card style. Here, they do several things: set the background color, create a black border, the width of the card, and the values for a shadow around it.

There's more...

With variables and functions already set, the last thing to do is call the canvas element itself in the HTML to give it all a space in which to run:

<canvas id="display" width="1000" height="650"></canvas>

Evil of two lessors

In the old days of the web, the Carbon Five team would have had the choice of leaving their map on a physical wall or creating a static graphic image of it for computer display. While either might render just as well as using the new canvas element, neither of them allow the team to extract valuable information the way the new canvas element does.

What about fallback content?

Interestingly, Carbon Five used no fallback content within the new canvas element in this instance. This is an approach you'll have to weigh carefully, as those with older browsers or who use assistive technologies will see nothing, literally nothing. Carbon Five gets away with that for this internal project. Can you?

See also

Jacob Seidelin hit another home run with his new canvas element visualization of the band Radiohead's song "Idioteque" from the album "Kid A" at: http://nihilogic.dk/labs/canvas_music_visualization. Jacob's pushing the limits of what can be done with the canvas element and JavaScript – and that's why we think he's terrific!

Bouncing a ball

We've looked at how do draw shapes using the new canvas element, and next we'll turn our attention to making those shapes move. Author Vinci Rufus shows us how.

As you can see, the ball is in motion but has simply drawn a straight line off the edge of the canvas. Vinci explains why:

"This is because each time the draw() function is called, it draws a circle at the new coordinates without removing the old ones. That's how the getContext object works so it's not a bug; it doesn't really move the circle and, instead, it draws a circle at the new coordinates each time the function is called."

Start again

Vinci shows us a method to erase the old circles as the new canvas element draws each new one:

Now, the ball appears to fall down to the right outside of the canvas border.

Don't box me in

To ensure that the ball stays within the border of the canvas, Vinci wrote some logic to check if the x and y coordinates are beyond the canvas dimensions. If they are, he makes the ball reverse directions.

See also

A beautiful example of user-generated graphics can be seen at Yuri Vishnevsky's http://weavesilk.com. The site uses the new canvas element as part of an experiment in generative art. Some of the generated images are so beautiful, Yuri has made them available as stunning desktop background images. A version for iPhone and iPad is planned also.

Summary

In this article, we took a look at real-life examples of setting up the canvas environment, understanding the 2d rendering context, processing shapes dynamically, drawing borders for images using canvas, creating interactive visualizations, and bouncing a ball.

Alerts & Offers

Series & Level

We understand your time is important. Uniquely amongst the major publishers, we seek to develop and publish the broadest range of learning and information products on each technology. Every Packt product delivers a specific learning pathway, broadly defined by the Series type. This structured approach enables you to select the pathway which best suits your knowledge level, learning style and task objectives.

Learning

As a new user, these step-by-step tutorial guides will give you all the practical skills necessary to become competent and efficient.

Beginner's Guide

Friendly, informal tutorials that provide a practical introduction using examples, activities, and challenges.

Essentials

Fast paced, concentrated introductions showing the quickest way to put the tool to work in the real world.

Cookbook

A collection of practical self-contained recipes that all users of the technology will find useful for building more powerful and reliable systems.

Blueprints

Guides you through the most common types of project you'll encounter, giving you end-to-end guidance on how to build your specific solution quickly and reliably.

Mastering

Take your skills to the next level with advanced tutorials that will give you confidence to master the tool's most powerful features.

Starting

Accessible to readers adopting the topic, these titles get you into the tool or technology so that you can become an effective user.

Progressing

Building on core skills you already have, these titles share solutions and expertise so you become a highly productive power user.