Mention RGraph on Twitter

RGraph: HTML5 Javascript charts library - What is HTML5 canvas?

Introduction

HTML5 canvas is a new HTML tag (<canvas>) which is part of the forthcoming HTML5 standard. It allows bitmap drawing which is controlled using Javascript, and is what the RGraph libraries use to draw the charts. You could liken it to a piece of paper which is part of your HTML page, on to which you can draw. Because you use Javascript to draw on the canvas it becomes part of your page and allows interaction very easily.

Canvas uses a "fire and forget" drawing methodology - there is no DOM that is maintained, so if you want to alter something you will probably have to redraw the entire canvas. The lack of a DOM means that canvas is fast to draw on and very responsive - important when you're providing iteractive charts to your users.

History

HTML5 canvas was originally introduced by Apple for use in WebKit (which is used in their Safari browser and Google Chrome). It is now part of the HTML5 specification and supported by the majority (if not all) of modern web browsers.

Example

[No canvas support]

The example to the right is a very simple case of drawing a few primitives on the canvas. The dotted border is provided by CSS to illustrate the drawing area.

The <canvas> tag itself is defined with just a width/height/id attribute. The one here also has a style attribute to make it more evident in the page. The HTML used is shown below:


<canvas id="cvs" width="375" height="250">[No canvas support]<canvas>
The content in between the tags is not shown if the browser supports canvas, and is if the browser doesn't. This provides for fallback content if the users browser doesn't support canvas.

HTML5 Canvas compared to SVG

HTML5 canvas can be compared (a bit) to SVG - which is a vector based alternative for drawing in HTML pages. SVG is at a more abstract level than canvas and maintains a record of everything drawn, using a DOM. This is then converted to a bitmap when shown. In the above example, if the blue squares coordinates are changed (eg in an animation), then the whole canvas needs to be cleared and redrawn for each frame.

As a result of not having to maintain a DOM <canvas> is fast to draw on and display to the browser.

Browser support for HTML5 canvas

The majority of current browsers support canvas, including IE9. Earlier versions of MSIE have some support through compatibility layers provided by Google and Mozilla. One such library - ExCanvas - is provided in the RGraph archive allowing IE8 to display the graphs, albeit without many of the dynamic features. You can read more on this here.

Full documentation »