Ajax JavaScript CSS HTML 5 DOM


Canvas is an HTML tag which is not part of version 4 and is thus not implemented on all browsers, but it is in Firefox and can thus be used with XUL. It makes it possible to draw on a part of the interface, and thus adds to XUL one of the major features of XAML.
In addition it belongs to the HTML 5 specification in progress.
To use canvas, it is initially necessary to add the definition of the HTML namespace to the window:

xmlns: html="http://www.w3.org/1999/xhtml"

Using canvas

The tag is integrated in the XUL file with the HTML prefix:

<html:canvas id="MyCanvas" width="400" height="300">

The width and the height of the canvas have been defined with the width and height attributes. A identifier was also assigned to give access to the element from JavaScript.
In the XUL part, the insertion of the element is all which is needed to create a drawing surface. The contents will be entirely created in JavaScript code.

This one always begins with the definition of graphic context:

1) Finding the object:

var canvas = document.getElementById("MyCanvas");

2) Giving it a graphic context:

var cg = canvas.getContext("2D");

The parameter indicates that the canvas uses 2D functions.
The functions are methods of the graphic object, for example:

cg.strokeStyle = "green"; 

One defines the color of the shape, actually green, and one draws a rectangle at location 20 and 20, with a height and a width of 50 pixels.

Functions of canvas

Giving the list of the functions of drawing on canvas goes beyond the scope of this tutorial, because it is a tag which is not native to XUL, but an object of Gecko and which will become further a part of HTML. One can find a tutorial on this object on the site of Mozilla.
We created a function of circle, and used a function of rounded rectangle given as example on the Mozilla site. If one wants to use canvas in production, it should be better to continue in this way and to create an interface to each function implemented on Gecko, for a future re-use in HTML 5.


The example draws various figures on a background.

License: (c) -2007 Xul.fr