Store and Use Values in Variables
In this example, we use variables to draw a small rectangle next to a larger
rectangle. The larger rectangle is twice as wide and twice as tall as the small
rectangle. We fill the small rectangle with the color
'BurlyWood'
and the larger rectangle with the color
Coral
.
We start by declaring and assigning values to the variables
x
,
y
,
and
w
.
var x = 40;
var y = 20;
var w = 50;
We also declare and assign a value to the variable
h
,
but instead of assigning it a number, we use an expression to calculate its value.
Since the value of
w
is 50, the value of
1.5 * w
is 75, so the value of
h
is 75.
var h = 1.5 * w;
Changing the value of
w
after assigning the value of
1.5 * w
to
h
does not change the value of
h
.
The value of
h
would still be 75 because it stores the value of the expression, not the expression itself.
We then use the values stored in
x
,
y
,
w
,
and
h
to draw the small rectangle.
context.fillRect(x, y, w, h);
To draw the larger rectangle, we calculate and assign new values for our variables.
For example, the x-coodinate of the larger rectangle is the x-coordinate of the small
rectangle plus the width of the small rectangle, and the width of the larger rectangle
is twice the width of the small rectangle.
x = x + w;
w = 2 * w;
h = 2 * h;
Note that we did not re-declare our variables before assigning new values to
them. Variables should only be declared once.
Also, the order of these calculations and new assignments can be important. If we had assigned a new
value to
w
before assigning a new value to
x
,
the x-coordinate of the larger rectangle would be too far to the right.
When we draw the larger rectangle, we use the same variables, but all of them have
new values except for the variable
y
.
context.fillRect(x, y, w, h);
By using variables to calculate its size and position, the larger rectangle is
always next to the small rectangle and it is always twice as wide and twice as
tall as the small rectangle. Change the intial values for
x
,
y
,
and
w
to see what happens.
To learn more about the coordinate system and drawing rectangles, visit the
Coordinates
and
fillRect()
lessons.
Quick Reference:
Coordinates
fillRect()
fillStyle