HTML and CSS Reference
In-Depth Information
Next, we create a simple array of dynamic objects that represents the colors of the gradient
( color ) and the stop percentages for the gradient fill ( stopPercent ). This will act as a very
simple “display list” of colors. Recall that since the Canvas runs in immediate mode and has
no display list of objects, we need to simulate that functionality.
Color stops are a percentage of the gradient fill. We will start with red and then add yellow,
blue, green, purple, and red again. We add red twice so that the color flows back to the begin-
ningandlooksfluid.Notice that thepercentages forbothredsareonly1/2oftheothers(.125,
instead of .25):
var
var colorStops = new
new Array (
{ color : "#FF0000" , stopPercent : 0 },
{ color : "#FFFF00" , stopPercent : . 125 },
{ color : "#00FF00" , stopPercent : . 375 },
{ color : "#0000FF" , stopPercent : . 625 },
{ color : "#FF00FF" , stopPercent : . 875 },
{ color : "#FF0000" , stopPercent : 1 });
Next, inside the drawScreen() function, we create the gradient. First we set up a gradient on
thecurrentpath.Theargumentstothe createLinerGradient() functionrepresentthe“line”
that the gradient will follow. Because we want the gradient to be in a straight vertical line, we
center it in the middle of the canvas and draw it directly down to the bottom:
var
var gradient = context . createLinearGradient (
theCanvas . width / 2 ,
0 ,
theCanvas . width / 2 ,
theCanvas . height );
Next, we loop through the colorStops array calling gradient.addColorStop() for each
colorinthearray.Agradient colorstopmethodhastwoarguments: the color andthe percent-
age . We already initialized these values in our array of dynamic objects, so now they are just
applied in a loop.
After each gradient color stop is added, we increment the percentage of each color by .015 .
This effectively moves the color “down,” because the greater the percentage, the larger the
colors fills in the gradient. Because we are changing all of the colors each time, the effect
is that they are all moving down in unison. If the gradient color stop percentage value goes
above 1 , we set it back to 0 , which moves it back to the top of the gradient:
for
for ( var
var i = 0 ; i < colorStops . length ; i ++ ) {
var
var tempColorStop = colorStops [ i ];
var
var tempColor = tempColorStop . color ;
var
var tempStopPercent = tempColorStop . stopPercent ;
Search WWH ::




Custom Search