HTML and CSS Reference
In-Depth Information
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 alpha value of the fill color:
context.fillStyle = rgba(255,0,0,1);
The alpha value can be from 1 (opaque) to 0 (transparent).
Filling Shapes with Gradients
There are two basic options for creating gradient fills on the canvas: linear and radial.
A linear gradient creates a horizontal, vertical, or diagonal fill pattern; the radial variety
creates a fill that “radiates” from a central point in a circular fashion. Let's look at some
examples of each.
Linear gradients
Linear gradients come in three basic styles: horizontal, vertical, and diagonal. We con-
trol where colors change in our gradient by setting color stops at points along the length
of the object we wish to fill.
Example 2-14 creates a simple horizontal gradient, as shown
Linear horizontal gradients.
in Figure 2-23 .
Example 2-14. A linear horizontal gradient
function drawScreen() {
// horizontal gradient values must remain 0
var gr = context.createLinearGradient(0, 0, 100, 0);
// Add the color stops.
gr.addColorStop(0,'rgb(255,0,0)');
gr.addColorStop(.5,'rgb(0,255,0)');
gr.addColorStop(1,'rgb(255,0,0)');
// Use the gradient for the fillStyle.
context.fillStyle = gr;
context.fillRect(0, 0,100,100);
}
Search WWH ::




Custom Search