Rey Bango

Web developer, honey badger

Canvas Baby Steps: An Introduction to the HTML 5 Canvas Element

I hate to admit it but I haven’t looked at <canvas> yet. It’s not for lack of wanting but more of time. Seems like there’s SO many cool things out there to learn and nailing down time is tough. So I decided to dip my toe into.

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 great 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> 

Category: HTML5, JavaScript

Tagged:

7 Responses

  1. Mike Taylor says:

    Hey Rey,
    `
    Nice introductory post! One thing to not is that `var myCanvas = $( “#can1″ );` doesn’t actually create a reference to the canvas element, but returns a jQuery object–so you won’t be able to do myCanvas.getContext(‘2d’). If you wanna go the jQuery way, you’ll need to access the actual DOM element like so: `var myCanvas = $( “#can1″ )[0];`, then you can grab the 2d context from that. :)

  2. Cardin says:

    The browser itself is the plugin. Without the browser’s native Javascript “plugin” it wouldn’t load. It’s an unfortunate twist of mindset, but I hope with Chrome’s integration of Flash, Flash might become to be viewed as part of a browser, rather than a separate component.

  3. Thanks Rey – I’ve been meaning to learn about CANVAS for months now – and this post was a perfect explanation.

  4. […] Canvas Baby Steps: An Introduction to the HTML 5 Canvas Element (Rey Bango) […]

  5. […] Canvas Baby Steps: An Introduction to the HTML 5 CanvasĀ Element […]

Learn JavaScript!

What to Read to Get Up to Speed in JavaScript.

The best books & blogs for learning JavaScript development. Broken down by experience levels!


My BIG LIST of JavaScript, CSS & HTML Development Tools, Libraries, Projects, and Books.

Constantly updated with the latest and greatest tools. Check it out!

Categories

Rey Bango is Stephen Fry proof thanks to caching by WP Super Cache