Using the canvas element is easy, but you do need a basic understanding of HTML and JavaScript.

Support for Canvas

Not all modern browsers support the canvas element, but is supported in Firefox 1.5 and later, Opera 9 and later, newer versions of Safari, Chrome, and Internet Explorer 9.

Begin with the Canvas

The element represents a rectangular area on an HTML page. When using the element, the first thing you need to do is add the tag to your HTML5 document: With the canvas element, you will always want to specify an id attribute because you will reference it from your JavaScript code. In addition, specify width and height attributes to define the size of the canvas. You can style the canvas element, and have more than one in your document. What do you do if the browser does not support the canvas element? There are a few options. An easy approach is to place alternative content inside the canvas tags. For example:

Example

You can place text, an image element, or whatever HTML content you need to display if the canvas tag is not supported. If the browser supports the canvas tag, the contents inside will be ignored. If the browser does not support the canvas tag, the contents will be displayed. An alternative to this approach is to test the browser for this feature ability using JavaScript. For example, you can create a function that tests the ability to create a canvas element. Then, based on the results, you can take specific actions. Here is an example regarding how to check for canvas support using JavaScript. In the following example, we use a conditional statement, to test for support.

Draw Onto the Canvas

To draw onto the canvas, we will need the assistance of JavaScript.

Canvas Coordinates

The canvas is a two-dimensional grid. The upper-left corner of the canvas has a coordinate of (0,0). In the previous example, we use the fillRect property and instructed the browser to start the X coordinate of 75 and the Y coordinate of 50. Then move 150 pixels to the left on X and down 100 pixels on Y, then fill the rectangle with a solid color.