Zend Certified Engineer

phpguru.org

Quality PHP, Javascript and C# code

Firefox 3

Intro to the new HTML5 CANVAS tag, its API and an example

Introduction

Internet Explorer does not support the canvas tag yet.
Try using Firefox.
A line graph created using RGraph

The new HTML5 CANVAS tag is a new tag for HTML5 that allows 2-dimensional drawing, or bitmap drawing if you like, using Javascript. It allows both simple and complex shapes to be drawn that you could previously only get by using images. It's what my RGraph graphing library is based on.

Browser support

The CANVAS tag is part of HTML5, and as such only supported by some browsers. Most of them, but not all. They are:

  • Mozilla Firefox
  • Google Chrome
  • Apple Safari
  • Opera

Because Microsoft Internet Explorer doesn't yet support it, it's not really feasible to use it for mainstream use. The canvas tag is in the HTML5 specification though, so it's just a matter of time.

Example

The graph to the top-right is produced using the CANVAS based RGraph - my HTML5 graphing library. This is an example of how you can use the new tag to produce things that you could previously only use images or plugins for. You will notice that it's quite fast. Subsequent page refreshes will be even faster because the library will be cached, and you will only have to download a few hundred bytes of data.

How to use the canvas tag

The new tag is very easy to use, and boils down to two steps:

  1. Define the tag
  2. Script it

For example:

<canvas id="myCanvasTag" width="100" height="100" style="border: 1px gray dashed">
    [Content that is shown to users using browsers that don't support the canvas tag]
</canvas>
<script type="text/javascript">
<!--
    window.onload = function ()
    {
        var myCanvas  = document.getElementById("myCanvasTag")
        var myContext = myCanvas.getContext('2d');

        myContext.fillStyle = 'yellow';            // Regular colour (yellow)
        myContext.fillRect(5,5,90,90);             // x, y, width, height

        myContext.fillStyle = 'rgba(255,0,0,0.5)'; // CSS style colour with alpha (transparency)
        myContext.fillRect(10,10,80,80);           // Another filled rectangle
    }
// -->
</script>

This is just a small example. There's another, working, example here. Or alternatively, just look at my graphing software - RGraph, which is based around the canvas element.

Using it isn't hard. First you get a reference to the HTML tag in the usual way using document.getElementById(), then get a reference to the context (there's only one at the moment - 2d. After you've done that you can manipulate it using the properties and methods made available to you via the context object. If you want a reference to what's available to you, consult the HTML5 specification. But suffice to say there are methods and properties for controlling colour, drawing lines, drawing arcs.

Perhaps unsurprisingly, there's discord when it comes to text. The HTML5 specification does account for text, but at the time of writing no browser implemented these. Fortunately whilst writing the RGraph library I used the CanvasText.js code, and adapted it. Eventually this will not be needed as browsers eventually support native text drawing.

The canvas objects API (well, the contexts really)

This is not complete by any means, listing the most commonly used methods and properties. If you want a complete reference I suggest you consult the W3C HTML5 specification.

  • moveTo(x, y)
    Moves the "pen" to the given x/y coordinates

  • lineTo(x, y)
    Draws a line to the given x/y coordinates.

  • strokeRect(x, y, width, height)
    Draws a rectangle, but does not fill it.

  • fillRect(x, y, width, height)
    Draws a rectangle and fills it.

  • beginPath()
    Begins a new path, with an empty set of sub-paths

  • closePath()
    Marks the current sub-path as closed and creates a new subpath

  • save()
    Saves the current pixel state on to the state stack. If for example you call save(), translate, draw something, and then call restore(), the co-ordinate system will be as it was.

  • restore()
    Resets the co-ordinate system to as it was when you called save() last. If you haven't, then this method will do nothing.

  • arc(x, y, radius, startAngle, endAngle, anticlockwise)
    Perhaps unsurprisingly, this method draws an arc. If you haven't yet stroke()ed, then you will get a line from the last point of what you've drawn to the start of the arc.

  • fill()
    Fills what you're drawing with the current fillStyle setting.

  • stroke()
    Strokes what you're currently drawing.

  • lineWidth
    I'm sure you can guess. it's a property that controls how thick the lines are drawn.

  • lineCap
    A proprty that controls how the ends of lines are drawn. Not really a big deal if your lines are thin, but it's noticeable when lines are thicker.

  • lineJoin
    Determines how browsers will draw the join of two lines. ie Round or square.

  • scale(x, y)
    Scales the canvas (ie the x/y coordinates)

  • rotate(a)
    Rotates the canvas. A common gotcha is that the angle that you give should be measured in RADIANS. 1 radian is equal to 57.296 degrees.

  • translate(x, y)
    Moves the coordinate system by the given x and y amounts. So if you translate by 10 pixels in the X direction and 10 pixels in the Y direction, 0,0 will bedrawn in the same place as 10,10 would have before the translation.

  • transform(m11, m12, m21, m22, dx, dy)
    The transform() method is used for matrix operations.

  • setTransform(m11, m12, m21, m22, dx, dy)
    The setTransform() method is used for matrix operations.

Possible uses

The obvious use is graphing, but you could also use it for a multitude of other things, like games or animation (using the Javascript setTimeout() function). You could quite easily use it to implement your own <marquee>!

Related links

Counter

Last modified: 12:35 28th December 2008