Draw a Smaller and Darker Row of Random Buildings
In addition to making the rows in the back smaller, we will also make them darker.
There are several ways to define colors when using the
context.fillStyle
property. So far, we have used the color
'#999999'
to draw our buildings. Another way to describe the color
'#999999'
is
'rgb(153, 153, 153)'
.
The number 153 in base 10 is actually 99 in base 16.
When using RGB values to define a color, we are describing the amount of red (r), green (g),
and blue (b) in the color, where 0 is none and the maximum value is 255. For example, the color
black
is
'rgb(0, 0, 0)'
,
which is no red, no green, and no blue; and the color
white
is
'rgb(255, 255, 255)'
,
which is maximum red, maximum green, and maximum blue.
In this example, we draw a rectangle with a random color by selecting and combining
random amounts of red, green, and blue.
There are a few things to keep in mind when using RGB values to define a color. First, the red,
green, and blue values have to be integers between 0 and 255. No decimals. Second, the
'rgb()'
format is a string of text. It may look like a function call, but it isn't. To build a string of
text from the three random integers stored in variables
r
,
g
,
and
b
,
we use the
+
operator to combine bits of text:
var color = 'rgb(' + r + ', ' + g + ', ' + b + ')'; // Combine the red, green, and blue in a text string
Press "Run" to change the color of the rectangle.
To learn more about describing fill colors and loose-typing of variables, visit the
fillStyle
and
Variables
lessons.
Quick Reference:
Variables
fillRect()
fillStyle
random()
round() / floor() / ceil()