Lesson 1: Drawing by using the
Configuring the drawing state
In the previous example, what is the fill color when calling fillRect? What is the line thickness
and color when calling strokeRect? The canvas context has properties that you can set before
you call any of the drawing methods. After you change a property, the new value is used for
subsequent drawing statements.
Setting fillStyle
Use the fillStyle property to specify how you want to fill shapes. You can set fillStyle to one of
the following values.
■■CSS color reates a solid color fill based on a valid CSS color value such as black, red, C
or #00FF00. The following is an example of setting fillStyle by using a CSS color value.
function drawUsingCssColor() {
var canvas = document.getElementById('myCanvas')
, ctx = canvas.getContext('2d')
, offset = 10
, size = 50;
ctx.fillStyle = "red";
ctx.fillRect(offset + (0 * (offset + size)), offset, size, size);
ctx.fillRect(offset + (1 * (offset + size)), offset, size, size);
ctx.fillStyle = "#00FF00";
ctx.fillRect(offset + (2 * (offset + size)), offset, size, size);
ctx.fillRect(offset + (3 * (offset + size)), offset, size, size);
ctx.fillStyle = "rgba(0, 0, 255, 0.25)";
ctx.fillRect(offset + (4 * (offset + size)), offset, size, size);
ctx.fillRect(offset + (5 * (offset + size)), offset, size, size);
}
In this example, fillStyle is set to “red”, and two rectangles are created. Next, fillStyle is
set to green, using “#00FF00”, and two rectangles are created. Finally, fillStyle is set to
blue with opacity of 25 percent, using “rgba(0,0,255,0.25)”, and two rectangles are cre-
ated. The results are shown in Figure 12-2.