HTML5:Canvas

Create a basic Rectangle
The  element is part of HTML5. It allows, in combination with scripting (usually JavaScript), the ability to draw dynamic shapes and images. It can be used for drawing graphs, animating images and game creation. (The  element was first introduced by Apple and used with the Mac OS X dashboard).

The  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  will default to a size of 300px wide and 150px high. You can also specify an  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  and   inside a   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.

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, then draw the path that makes up your shape using lines and curves. once complete, fill and stroke if desired, then call  to complete.

The following example creates a shape combining lines and a circle.

Angles in the  function are measured in radians, not degrees. To convert degrees to radians you can use the following JavaScript expression: .

And this is what it looks like in an HTML5 ready browser



Animating Shapes
now the fun part...coming soon :)

Resources
HTML5 Canvas - The Basics