<canvas> element – provides a bitmap area for drawing of shapes and rendering of images.

Usage: typically used for display of data or interactive data. Also used for games. One must use JavaScript at the moment to define most interactions with the <canvas> element. In the examples below, note the use of a unique identifier (id=”canvas”. for example) to provide a coding “hook” for JavaScript interactions.

Permitted Content: global attributes and height and width attributes.

Tag omission: both start and end tag must be present. It is also a good idea to include alternate content for those browsers which do not support the <canvas> element.

Example code:

<canvas id=”canvas” width=”500″ height=”500″>
<p>This example requires a browser that supports the <a href=””>HTML5</a> &lt;canvas&gt; feature.</p>

Example pages (each opens in a new tab/ window – view source code):

Default display properties: a blank area on the document (one can style this with CSS).

JavaScript notes:

One should always test for support for the <canvas> element.

if (canvas.getContext) {
// code to draw within element would be placed here

One should always save the current context, perform various actions, and then restore the current context. Otherwise, some browsers may behave oddly. Note that all of the linked examples work with 2D context – 3D is not supported in many browsers yet.

var canvas_context = canvas.getContext(“2d”);

To draw simple objects one chooses an option at a time. Think in terms of lifting a pencil, placing it in a specific spot on the document and then drawing the shape. In the code below, we draw a red rectangle starting at x=10, y=10 and drawing to x=300 and y=300. We always start in the top left and draw across and down (default).

canvas_context.fillStyle = “rgb(200,0,0)”;
canvas_context.fillRect(10, 10, 300, 300);

Common Attributes:

  • id=”canvas” – to associate <canvas> element with JavaScript code.

Update July 30, 2012 – I attended the Adobe Education Leader Summer Institute last week and Mark Shufflebottom provided an example of what one can create using Flash CS6 Professional and CreateJS. With his permission, I provide his example. One must install the CreateJS extension into Flash and then publish (which will generate necessary script and canvas elements). Think of Flash as being used to create the animation and CreateJS being used to generate the canvas contents. Don’t forget to view the source code to see what is going on. I also encourage you to try out various browsers (hint – the sound will play in Safari).


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.