|Table of contents|
By the end of this page you will be able to:
HTML5 and the <canvas> element
Create a basic Rectangle
<canvas> element was first introduced by Apple and used with the Mac OS X dashboard).
<canvas> element has two attributes only, height and width. These attributes can be set inline or via CSS. When no height or width attributes are specified, the
<canvas> will default to a size of 300px wide and 150px high. You can also specify an
id as well as applying other styles such as margins and borders.
The basic code for specifying the canvas area of 200px x 200px is:
Canvas only supports one shape - rectangles. All other shapes must be creating by defining paths, which allow creation of simple and complex shapes. The position of shapes is defined by their x and y coordinates, the upper most left hand side of the canvas element being the 0,0 position.
There are three functions that draw rectangles:
The following example uses
strokeRect inside a
createShape() function to draw an outlined rectangle inside the canvas and specify the fill colour. The shape is drawn 10px in on the x axis, 10 down on the y axis and the width and height are equal at 100px each. The stroke outline sits at exactly the same place. Copy and paste the code into a text editor and view in an HTML5 supported browser. Change around the coordinates and size of both the shape and the stroke as well as the fill color to see how it all works.
Using Paths to Create Complex Shapes
Lines and Circles
Paths allow you to draw shapes (other than rectangles). Firstly you draw an outline, then choose to stroke and fill as necessary. To start drawing the path, use
beginPath(), then draw the path that makes up your shape using lines and curves. once complete, fill and stroke if desired, then call
closePath() to complete.
The following example creates a shape combining lines and a circle.
And this is what it looks like in an HTML5 ready browser
Bezier and Quadratic Curves
now the fun part...coming soon :)
HTML5 Canvas - The Basics 
- Sugan, M. (2009). HTML 5 Canvas - The Basics, retrieved 11 September 2010, from http://dev.opera.com/articles/view/html-5-canvas-the-basics/