HTML and CSS Reference
drawing on and transforming the canvas. The graphical capabilities of the canvas en-
compass the following:
• Basic drawing : There are methods for drawing rectangles, lines, curves, and
• Fills and strokes : There are methods for creating solid fills and outlines.
• Effects : There are methods for creating shadows, gradients, transparency, and
for compositing images on top of each other.
5 The WHATWG runs a wiki at http://wiki.whatwg.org/wiki/ CanvasContexts that provides an
overview of the canvas context keywords available.
6 The WebGL specification is available here: www.khronos.org/registry/webgl/specs/latest/.
• Transformations : There are methods for scaling, rotating, and translating (mov-
ing) the image.
• Text : There are methods for adding solid or outlined text.
• Images : There are methods for drawing an image (or even a video or another
canvas element) onto the canvas, which can then be transformed or otherwise
We will explore the first two areas, but be sure to use the console to explore the meth-
ods and properties available that are not covered in this chapter. The purpose of many of
them is quite self-evident!
Drawing on Canvas
Let's begin by drawing a rectangle on the canvas that covers the available area. The
methods related to drawing a rectangle are as follows:
• fillRect(x,y,w,h) : Draws a solid rectangle
• strokeRect(x,y,w,h) : Outlines a rectangle
Using either of these methods, we can create a rectangle of a given width and height
starting at a specified location on the canvas. Before using these methods, you may want
to style the rectangle to specify the appearance of the fill and stroke (the outline color).
There are a few properties that can be set for this purpose:
• fillStyle : The fill color
• strokeStyle : The color of the outline
• lineWidth : The width of the outline