An Introduction to the HTML5 Canvas
HTML5 is the World Wide Web Consortium’s (W3C’s) proposed specification for the next generation of the web. It’s the operating manual covering the workings of browsers, search robots, and other web software. After 10 years of relative stagnation in web evolution, HTML5 is a remarkable achievement with many new document elements, attributes and features. The canvas element is one of these.
The Canvas Challenge to Flash
The HTML5 canvas provides an open platform for graphical applications within the context of the web page. Because the canvas API is built into an HTML5 browser, canvas applications should perform better than plugin-based technologies, such as Adobe's Flash, especially on devices that can take advantage of hardware graphics acceleration.
Unlike a Flash application, a canvas-based app is a true HTML element. It can be styled with CSS and can interact with other page elements and scripts, including the HTML5 audio and video elements. Multiple canvases can be superimposed in switchable layers.
The canvas element is simple, having no required attributes. It can be given a height and width to override the default of 300x150 pixels. In the canvas element shown above, an id attribute is set that will be used to reference it in the script. The canvas element has a start and end tag; the content inside is fallback markup for older browsers, search robots, and other user agents. The fallback content could include the object, embed, and param elements for a Flash application that would play in legacy browsers.
In the previous example, a CSS rule is used to render the canvas with a thin bottom border to serve as the x-axis of the bar graph. Following the HTML code for the canvas is the markup to create an input form for entering the height of each successive bar. The input element has an onchange attribute that calls a handler function to draw the bar each time the input value changes.
Figure 1 shows what this example looks like in Safari after a half-dozen numbers have been entered. It’s meant to be used with the number and enter keys on a keypad. The graphs can be screen-captured as images for use on blogs and in presentations. You can try out a working demo on my site.
Figure 1 A fast bargraph generator using an HTML5 Canvas element.