Setting Basic Fill Colors

The Canvas fillStyle property is used to set a basic color for filling shapes on the canvas. We saw this earlier in the chapter when we used simple color names for our fillStyle. An example is:

context.fillStyle = "red";

Below is a list of the usable color string values from the HTML4 specification. As of this writing, the HTML5 color specification has not been set. In the absence of any additional HTML5-specific colors, the HTML4 colors will work properly in HTML5:

Black = #000000
Green = #008000
Silver = #C0C0C0
Lime = #00FF00
Gray = #808080
Olive = #808000
White = #FFFFFF
Yellow = #FFFF00
Maroon = #800000
Navy = #000080
Red = #FF0000
Blue = #0000FF
Purple = #800080
Teal = #008080
Fuchsia = #FF00FF
Aqua = #00FFFF

Note

All these color values will work with the strokeStyle property as well as the fillStyle property.

Of course, using a string for the color name is not the only available method of specifying a solid color fill. The following list includes a few other methods:

Setting the fill color with the rgb() method

The rgb() method lets us use the 24-bit RGB value when specifying our fill colors:

context.fillStyle = "rgb(255,0,0)";

This will result in the same red color as the string value above.

Setting the fill color with a hex number string

We can also set the fillStyle color with a hex number in a string:

context.fillStyle = "#ff0000";
Setting the fill color with the rgba() method

The rgba() method allows us to specify a 32-bit color value with the final 8 bits representing the ...

Get HTML5 Canvas, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.