Tuesday, March 19, 2024

How to Use The HTML5 Canvas Element

This article continues our “mini-series” of important new elements in HTML5 to help you learn to create media-rich pages that will work in any compliant browser.


Canvas is a unique concept. Unlike the rest of the HTML world that consists of well-defined pieces that designers and developers love to place in exactly the right spot, the Canvas element provides a virtual Etch-a-Sketch-like area where almost anything can be made to happen. It’s relatively easy to describe but, like most open-ended concepts, more difficult to characterize. Canvas is a bit-mapped area whose width and height dimensions are specified as attributes (defaulting to 300 and 150 respectively); the purpose can be virtually anything, and the intention is that a canvas element will be rendered by scripting.

Show Me the HTML5 Code!


Clearly the simplest possibility is <canvas></canvas>, and that gets you your very own 300×150 area, but you won’t see it because the default is transparent (speaking of defaults, anything you actually draw on a canvas is black unless you specify otherwise). A more realistic beginning is something like this:

<canvas id=”drawme” width=”400″ height=”200″>
   If you can read this, your browser does not support Canvas.
<canvas>

Note that, similar to the video element, you can (and should) provide fallback content in case the browser doesn’t yet support the canvas element. Actually, it’s more than “should”…it’s “must” in the words of the W3C definition:


“When authors use the canvas element, they must also provide content that, when presented to the user, conveys essentially the same function or purpose as the bitmap canvas. This content may be placed as content of the canvas element.”


So in a real-world web page, you’d want to include something that displays the closest equivalent to the contents of your fancy bitmapped graphic canvas. If your canvas showed a stock graph, you could use the current stock price. The intent is to allow the widest possible audience to see the most valuable and useful content, after all. The good news is that the current versions of all leading modern browsers already support canvas…except, of course, Internet Explorer (though it’s coming in IE9).


Also, note that you must name each specific canvas element with its own id so you can address it later in your Javascript. And while most basic tutorials show all kinds of boxes and graphic elements laboriously rendered point by point, in reality most canvas applications will involve user interactivity, image transformations, or algorithm-based graphic rendering, such as Apple’s clock widget. Or all three, such as this mind-boggling Canvas Aquarium.

The Mozilla Developer Network Template


Mozilla’s Developer Network has created a nice template for use in demonstrating basic canvas functions, so we’ll use that as the basis of our own example code:

<!DOCTYPE html>
<html lang=”en”>
 <head>
   <meta charset=”utf-8″>
   <title>Canvas Tutorial Template</title>
   <script type=”text/javascript”>
     function draw(){
       var canvas = document.getElementById(‘tutorial’);
       if (canvas.getContext){
           var ctx = canvas.getContext(‘2d’);

//
//    drawing code goes below here
//
           ctx.fillStyle = “rgb(255,0,0)”;

           ctx.fillRect(0, 0, 150, 150);

//
//    drawing code goes above here
//

       }
     }
   </script>
   <style type=”text/css”>
     canvas { border: 1px solid black; }
   </style>
 </head>
 <body onload=”draw();”>

   <canvas id=”tutorial” width=”150″ height=”150″>
       Fallback content goes here.
   </canvas>
 </body>
</html>


You can see it in action here.


The most important piece of all this is actually where you call getElementById using your named canvas id (which locates your canvas in the DOM), then call getContext to initialize the actual drawing context. Once you have a context (which we point to using ctx), you can manipulate it using anything you like in the 2D drawing APIs.

And the Function Is….


In this case, we’ve used fillStyle to select solid red and fillRect to describe the boundaries of the rectangle to be drawn. You can now use this template to quickly experiment with any or all of the other functions in the APIs, by simply writing more complex code in place of those two lines. The x,y origin is defined to be at the top left, so knowing that, you can start making use of functions such as:

  • fillRect (x,y, width, height) – paints the described rectangle (filled using the current fillStyle)
  • strokeRect (x,y, width, height) – paints the described rectangle outline (using the current strokeStyle)
  • clearRect (x,y,width,height) – clears the described rectangle and makes it transparent (transparent black, to be technical)

For true drawing, you need the ability to draw lines and curves, and place your virtual pen anywhere on the canvas, so these functions are key:

  • beginPath() – starts a new drawing
  • moveTo(x,y) – places the pen at the x,y location
  • lineTo(x,y) – draws a line from the pen location to the x,y location
  • arc(x, y, radius, startAngle, endAngle, anticlockwise) – draws an arc at x,y using radius from startAngle to endAngle (in radians). The arc is drawn clockwise unless the optional boolean anticlockwise parameter appears.
  • stroke() – renders the drawing in outline form
  • fill() – renders the drawing in filled form

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Popular Articles

Featured