HTML5 Part 2: Canvas

blank-canvasAnother new element in HTML5 is the <canvas> tag.  It is essentially a blank surface for drawing.  You need to use JavaScript to manipulate and draw on the canvas.  

You may want to give your canvas element an id attribute so that you can programmatically access it from your JavaScript code (or if you are using jQuery and it was the only canvas on the page, you could access it using $(‘canvas’) without needing to name it).  You can also optionally specify a height and a width for the canvas.  Between the <canvas> and </canvas>, you can specify some text to display in browsers that don’t support the canvas element.  

Here is a simple example of using the canvas to draw.  (I’m attempting to draw the flag of Scotland.  Please forgive any inaccuracies.) 

 <!DOCTYPE HTML>
<html>
<body>
    <canvas id="myCanvas">Your browser does not support the canvas tag.</canvas>
    <script type="text/javascript">

        var canvas = document.getElementById('myCanvas');
        var ctx = canvas.getContext('2d');

        // Draw blue rectangle
        ctx.fillStyle = '#2222FF';
        ctx.fillRect(0, 0, 125, 75);

        // Draw white X
        ctx.beginPath();
        ctx.lineWidth = "15";
        ctx.strokeStyle = "white";
        ctx.moveTo(0, 0);
        ctx.lineTo(125, 75);
        ctx.moveTo(125, 0);
        ctx.lineTo(0, 75);
        ctx.stroke();

    </script>
</body>
</html>

In case your browser doesn’t support HTML5, here is a screenshot of what this code produces:

image

Now let’s walk through the code.  First, I create the actual canvas and give it an ID of “myCanvas”.  If this code were viewed in a browser that doesn’t support the HTML5 canvas element, it would display “Your browser does not support the canvas tag.” instead of drawing the flag. 

Next, I have a script.  Remember that the canvas tag is only a container for graphics; you must use JavaScript to actually draw and render graphics on it.  First, I grab a reference to the canvas using the “myCanvas” ID, and then get the canvas’s context which provides methods/properties for drawing and manipulating graphics on the canvas.  I specified “2d” to use a 2-dimensional context to draw on the page. 

Then, I draw the blue rectangle.  I use fillStyle to specify the blue color (which is not perfect; apologies to the Scots).  I use fillRect to draw the rectangle, specifying the size and position.  Calling fillRect(0, 0, 125, 75) means: starting at position (0, 0) – the upper left-hand corner – draw a rectangle with width=125 pixels and height=75 pixels. 

Finally, I draw the white X on the flag.  I first call beginPath to start the process of painting a path.  I specify a lineWidth of 15 pixels (using the guess-and-check method of trying different values until it looked correct) and a strokeStyle of “white” to make the path’s color white.  Then I trace out the path using moveTo and lineTo.  These methods position a “cursor” for you to draw; the difference is that moveTo moves the cursor without drawing a line and lineTo draws a line while moving.  I start by moving to position (0, 0) – the upper left-hand corner – and then drawing a line to (125, 75) – the lower right-hand corner.  Then I move to position (125, 0) – the upper right-hand corner – and draw a line to (0, 75) – the lower left-hand corner.  Finally, the stroke method actually renders these strokes. 

Quick Comparison of Canvas vs. SVG

Scalable Vector Graphics (SVG) is an earlier standard for drawing in a browser window.  With the release of HTML5’s canvas, many people are wondering how they compare. 

In my eyes, the biggest difference is that canvas uses immediate mode rendering and SVG uses retained mode rendering.  This means that canvas directly causes rendering of the graphics to the display.  In my code above, once the flag is drawn, it is forgotten by the system and no state is retained.  Making a change would require a complete redraw.  In contrast, SVG retains a complete model of the objects to be rendered.  To make a change, you could simply change (for example) the position of the rectangle, and the browser would determine how to re-render it.  This is less work for the developer, but also more heavyweight to maintain a model. 

The ability to style SVG via CSS in addition to JavaScript is worth calling out as another consideration.  A canvas may be manipulated through JavaScript only. 

Here is a high-level overview of other differences: 

  Canvas SVG
Abstraction Pixel-based (dynamic bitmap) Shape-based
Elements Single HTML element Multiple graphical elements which become part of the Document Object Model (DOM)
Driver Modified through Script only Modified through Script and CSS
Event Model User Interaction is granular (x,y) User Interaction is abstracted (rect, path)
Performance Performance is better with smaller surface and/or larger number of objects Performance is better with smaller number of objects and/or larger surface

For a more detailed comparison, I want to point you to some sessions (from which I pulled this fabulous table, with permission): Jatinder Mann’s “Deep Dive Into HTML5 Canvas” from MIX 2011 and John Bristowe’s “An Introduction to HTML5 Canvas”. 

Tomorrow, we will discuss the new HTML5 elements <audio> and <video>

 

Other blog posts in this series:

  1. HTML5 Part 1: Semantic Markup and Page Layout
  2. HTML5 Part 2: Canvas
  3. HTML5 Part 3: Audio and Video
  4. HTML5 Part 4: Using HTML5 while retaining support for older browsers
  5. HTML5 Part 5: Resources, Websites, and Tools