HTML and CSS Reference
This code creates a canvas element and adds a randomly colored and sized square onto the page every 50
milliseconds. Clicking or touching the canvas element calls the toDataURL method, creates a new <img>
tag, sets the src attribute to that URL, and then prepends that <img> tag to a snapshots <div> . Each click
generates a new image, and because the width of the <img> is set to 100 , you can see a time lapse of how the
Canvas changes with each click you make.
The W3C specification also defines a toBlob method that outputs a File object, which saves on memory
because the file may be written to disk and is easier to work with. Unfortunately, as of this writing that method
is not implemented in any browser, so it should be avoided. (Firefox defines a mozGetAsFile method, but
this is nonstandard and uses a different syntax.)
Drawing on Canvas
The Canvas context provides a number of different ways to draw onto the <canvas> element. The four
primary methods are drawing rectangles, paths, text, and images. (The context also has methods to modify pixel
data directly that are discussed in Chapter 17, “Playing with Pixels.”) With the exception of the images, the
other drawing methods can be drawn as a stroke , meaning only the outline is drawn, or as a fill , meaning
the interior is drawn. Much like SVG, Canvas also has support for a number of different line join styles and end
caps. Also like SVG, Canvas can do strokes and fills using gradients and patterns.
Setting the Fill and Stroke Styles
The Canvas context keeps the state of the current stroke and fill styles in the strokeStyle and fillStyle
properties, respectively. These properties can be both read and written to. The simplest values you can set
for stroke and fill are CSS color values. These color values can be in the form of a normal pound-sign-
prefixed hexadecimal color string such as "#F00" or "#FF0000" , as an RGB triplet string in the form
"rgb(255,0,255)" , or as a named color such as "red" .
ctx.fillStyle = "teal";
ctx.strokeStyle = "rgb(128,64,64)";
ctx.fillStyle = "#FF0000";
// Logs the last value "#FF0000"
// Logs the strokeStyle converted hexadecimal as "#804040"
Both fillStyle and strokeStyle can also be set to gradients or patterns. Canvas supports two types
of gradients: linear and radial. These types are created by calling the chosen method on the context: