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".

For example:

ctx.fillStyle = "teal";

ctx.strokeStyle = "rgb(128,64,64)";

ctx.fillStyle = "#FF0000";

console.log(ctx.fillStyle); 
// Logs the last value "#FF0000"

console.log(ctx.strokeStyle); 
// 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: ...

Get Professional HTML5 Mobile Game Development now with O’Reilly online learning.

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