An Introduction to the HTML 5 Canvas Element

Rey Bango | September 1, 2010

 

For those not familiar with it, the HTML 5 <canvas> element provides a rectangular area where you can draw anything you want on. It's pretty slick and seems pretty powerful. In essence, instead of solely relying on image creation tools like Photoshop, GIMP or Paint.net for generating graphics, you now have a native element on which to do it.

If we look at the <canvas> element, the format is just like any other HTML element:

<canvas id="can1" width="300" height="300"></canvas>

You define the element along with specific attributes, just like most any other HTML element. In this case, we’re assigning it an “id” along with the width and height of the rectangular drawing area. The reason we assign it an “id” is to allow us to later reference the element via JavaScript and call the methods necessary to start drawing.

Now, I’m by no means a Picasso, which is why I tend to focus more on programming than design work. I prefer to leave that to the pros with a real creative knack but I will at least attempt to create something colorful.

The first thing we need to do is create a reference to the <canvas> element. Remember that I discussed adding an “id” attribute to the element? This is where it comes in handy:

var myCanvas = document.getElementById( "can1" );

You could do the same thing in jQuery this way:

var myCanvas = $( "#can1" )[0];

But because we really don’t need all of the jQuery library’s syntactic sugar for this small demo, I’m just going to use plain ‘ole JavaScript.

Next, we’ll use the element’s getContext() method to grab the rendering context for that element. This is the area within your <canvas> element where the actual drawing will occur. It doesn’t have to be the same size as your canvas but it needs to fit within it.

var myContext = myCanvas.getContext( "2d" );

We specify “2d” as a parameter because it’s the only rendering context currently supported by the specification so for now, you’re limited to flat drawings.

Now that I have the rendering context, I can begin making my drawing. Using the fillStyle and strokeStyle properties, I can set the fill color for specific areas of my drawing and the color of the borders respectively. Then using the strokeRect() & fillRect() methods, I can use the colors defined in those properties to effect the change:

myContext.fillStyle   = '#00f';
myContext.strokeStyle = '#f00';
myContext.lineWidth   = 4;
myContext.strokeRect( 0,0,300,300);
myContext.fillRect(0, 0, 300, 300);

What this does is gives me a nice blue box with a red border around it. It may not look like much but the fact that we’re able to do this via HTML and JavaScript is pretty cool:

Now I want to get fancy (well as much as I guess I can). I want to create a shape within the canvas rendering context so I’m first going to use the moveTo() method to position my starting point. The two parameters are “x,y” coordinates within your rendering context and I’d like to start at the top and centered:

myContext.moveTo( 150, 0 );

Next, I’ll use the lineTo() method to draw a line to different “x,y” coordinates. Notice that I don’t have to re-use the moveTo() method to reposition the starting point of each line.

myContext.lineTo( 0, 150 );
myContext.lineTo( 150, 300 );
myContext.lineTo( 300, 150 );
myContext.lineTo( 150, 0 );

This code renders a box like this:

The last things I want to do are to adjust the fillStyle and strokeStyle properties so that they’re a different color:

myContext.fillStyle   = '#F63806';
myContext.strokeStyle = "#000";

and then using the fill() and stroke() methods, apply the color changes to the new drawing:

myContext.fill();
myContext.stroke();

Wooo!! Okay, okay this is not going to land me a million bucks at an auction or even $1.50 on Esty but it's a start. While what I built is fairly simple, the power of <canvas> can really be seen by visiting Canvasdemos.com. Along with excellent demos built using <canvas>, it provides tutorials on how to get up to speed on this element.

One really cool thing is that the gaming industry is keenly looking at <canvas> since it will help them distribute new games without the need for special plugins. Here's a tutorial, for example, that talks about how to create a game using <canvas>. It certainly won't replace dedicated console or PC games but it does open up opportunities to build the next FarmVille or PacMan.

Here's the code to my tutorial:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <meta name="robots" content="noindex" />
  <title>Canvas Test</title>
</head> 
 
<body> 
 
<canvas id="can1" width="300" height="300"></canvas>
 
  <script type="text/javascript">
  var myCanvas = document.getElementById( "can1" );
  var myContext = myCanvas.getContext( "2d" );
  myContext.fillStyle   = '#00f';
  myContext.strokeStyle = '#F63806';
  myContext.lineWidth   = 4;
  myContext.fillRect(0, 0, 300, 300);
  myContext.strokeRect( 0,0,300,300);
 
  myContext.moveTo( 150, 0 );
  myContext.lineTo( 0, 150 );
  myContext.lineTo( 150, 300 );
  myContext.lineTo( 300, 150 );
  myContext.lineTo( 150, 0 );      
 
  myContext.fillStyle   = '#F63806';
  myContext.strokeStyle = "#000";
 
  myContext.fill();
  myContext.stroke();
 
  </script>
 
</body>
</html>

About the Author

As the Client-Web Community Program Manager for Microsoft, Rey focuses on building stronger awareness to client-side development and helping Microsoft meet the needs of this community. In addition, Rey is the Head of Evangelism for the jQuery JavaScript project and a writer for Ajaxian.com, the web's premier JavaScriptblog.

Known for his passion for JavaScript and jQuery, approachable demeanor, and community-centric focus, Rey works tirelessly to promote the benefits of the jQuery project and assist the community by ensuring they have the information necessary to be successful. He is well-respected within the JavaScript community for his desire to promote unity and cooperation within the various JavaScript projects and his contributions to Ajaxian.com.

Find Rey on: