HTML and CSS Reference
In-Depth Information
var
var
gr
=
context
.
createLinearGradient
(
0
,
0
,
100
,
0
);
The four parameter values in the
createLinearGradient
method call are the top-left
x
and
y
coordinates to start the gradient, as well as the two bottom-right points to end the gradient.
Our example starts at
0,0
and goes to
100,0
. Notice that the
y
values are both 0 when we
create a horizontal gradient; the opposite will be true when we create a vertical gradient.
After we have defined the size of our gradient, we then add in color stops that take two para-
meter values. The first is a relative position origin point along the gradient to start with color,
and the second is the color to use. The relative position must be a value from 0.0 to 1.0:
gr
.
addColorStop
(
0
,
'rgb(255,0,0)'
);
gr
.
addColorStop
(.
5
,
'rgb(0,255,0)'
);
gr
.
addColorStop
(
1
,
'rgb(255,0,0)'
);
another red color at
1
. This will fill our shape with a relatively even red to green to red gradi-
ent.
Next, we need to get the
context.fillStyle
to be the gradient we just created:
context
.
fillStyle
=
gr
;
Finally, we create a rectangle on the canvas:
context
.
fillRect
(
0
,
0
,
100
,
100
);
Notice that we created a rectangle that was the exact size of our gradient. We can change the
size of the output rectangle like this:
context
.
fillRect
(
0
,
100
,
50
,
100
);
context
.
fillRect
(
0
,
200
,
200
,
100
);
Example 2-15
adds these two new filled rectangles to
Example 2-14
to create
Figure 2-24
.
Notice that the gradient fills up the available space, with the final color filling out the area
larger than the defined gradient size.
Example 2-15. Multiple gradient-filled objects
function
function
drawScreen
() {
var
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)'
);