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:
The tag is integrated in the XUL file with the HTML prefix:
<html:canvas id="MyCanvas" width="400" height="300"> </html:canvas>
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
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"; cg.strokeRect(20,20,50,50);
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.
- Demo code.zip.