The Art & Science Of JavaScript76
issues, it has had problems escaping its reputation as a 90s-era CPU-hog that will crash your browser;
inaccurate as that may now be.
Fortunately, in the past couple of years an alternative technology has emerged that promises to
avoid the problems from which Flash and Java have sufferedthe canvas element.
The canvas element provides a browser-native method for specifying graphics that can be updated
with client-side scripting. Its been included as a proposed standard by the WhatWG,
an open
community of browser vendors and web developers, and is included in the HTML 5 specification.
canvas was originally designed by Apple to allow the WebKit component to create vector graphics.
WebKit is an open source browser engine thats utilized by a number of applications in Apples OS
X operating system, including Dashboard and Safari. Importantly for us, WebKit can be used to
render vector graphics, like the clock shown in Figure 3.1, inside the Safari web browser.
Canvas is now supported by Safari 2+, Opera 9+, and Firefox 1.5+ (and associated Mozilla builds).
Internet Explorer does not support canvas, but well look at solutions to this later in the chapter.
Figure 3.1. Apples dashboard clock, which uses canvas to draw and animate the clocks hands
Working with canvas
Canvas is a lot like an img elementit doesnt act as a container for any other elements, it just
functions as a space in which you can draw. Think of canvas as an image that you can draw onit
even supports exactly the same attributes as an img (except for src).
Including a canvas element directly into your HTML code is easy:
<canvas id="graph" width="400" height="400" />
Canvas elements are inline elements by default. If no width or height is specified, a canvas element
will automatically be sized to a width of 300 pixels and a height of 150 pixels.

Get The Art & Science of JavaScript now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.