HTML and CSS Reference
In-Depth Information
Depending on the institution, this could indicate grades of A, A-, B, C+, and B. The following snippet
computes the grade-point average and stores it in the variable named
gpa
. Notice that we need to initialize
the variable named
sum
to start with a value of 0. The
+=
operator adds to the value held in
sum
the value in
the
grades
array at index value
g
.
var sum = 0;
for (g=0;g<grades.length;g++) {
sum += grades[g];
}
var gpa;
gpa = sum/grades.length;
To produce what we need to build the gradient, the code extracts values from the
hue
array and uses them
to produce character strings indicating RGB values. We use the
hue
array along with a variable called
color
to set the color stops to define the gradient. The color stops are set at any point between 0 and 1,
using a
for
loop that sets
color
to be a character string of the required format, namely starting with
"
rgb(
", and including the three values.
for (h=0;h<hue.length;h++) {
color = 'rgb('+hue[h][0]+','+hue[h][1]+','+hue[h][2]+')';
grad.addColorStop(h*1/hue.length,color);
}
The assignment statement setting
color
may seem strange to you: theres a lot going on—and what are
those plus signs doing? Remember, our task is to generate the character strings indicating certain RGB
values. The plus signs do
not
indicate addition of numbers here but concatenation of strings of
characters. This means that the values are stuck together rather than mathematically added, so while 5+5
yields 10, '5'+'5' would give 55. Because the 5s in the second example are enclosed by quote marks, they
are strings rather than numbers. The square brackets are pulling out members of the array. JavaScript
converts the numbers to the character string equivalent and then combines them. Remember that its
looking at arrays within arrays, so the first number within square brackets (in this case, provided by our
variable
h
) gives us the first array, and the second number within square brackets gives us our number
within that array. Lets look at a quick example. The first time our loop runs, the value of
h
will be 0, which
gives us the first entry within the
hue
array. We then look up the separate parts of that entry in order to
build our final color.
After all that, our code has set up the variable
grad
to be used to indicate a fill pattern. Instead of setting
fillStyle
to be a color, the code sets it to be the variable
grad
.
ctx.fillStyle = grad;
Drawing the rectangles is the same as before, but now with the indicated fill. These are four narrow walls at
the left, right, top, and bottom of the original rectangle. I make the walls as thick as the radius of the ball.
This thickness is the width in the case of the vertical walls and the height in the case of the horizontal
walls.
ctx.fillRect(boxx,boxy,ballrad,boxheight);
ctx.fillRect(boxx+boxwidth-ballrad,boxy,ballrad,boxheight);
ctx.fillRect(boxx,boxy,boxwidth,ballrad);
ctx.fillRect(boxx,boxy+boxheight-ballrad,boxwidth,ballrad);