the width and height of the canvas. The second line sets the fill color, which is distinct
from the outline color (called the stroke in Paper.js parlance). Feel free to experiment
with changing those arguments.
Automating Repetitive Tasks
Consider what you’d have to do if you wanted not just to add one circle, but to fill the
canvas with them, laid out in a grid. If you space the circles 50 pixels apart and make
them slightly smaller, you could fit 64 of them on the canvas. Certainly you could
copy the code you’ve already written 63 times, and by hand, modify all of the coordi‐
nates so that they’re spaced out in a grid. Sounds like a lot of work, doesn’t it? Fortu‐
nately, this kind of repetitive task is what computers excel at. Let’s see how we can
draw out 64 circles, evenly spaced. We’ll replace our code that draws a single circle
with the following:
var
c
;
for
(
var
x
=
25
;
x
<
400
;
x
+=
50
) {
for
(
var
y
=
25
;
y
<
400
;
y
+=
50
) {
c
=
Shape
.
Circle
(
x
,
y
,
20
);
c
.
fillColor
=
'green'
;
}
}
If you refresh your browser, you’ll see we have 64 green circles! If you’re new to pro‐
gramming, what you’ve just written may seem confusing, but you can see it’s better
than writing the 128 lines it would take to do this by hand.
What we’ve used is called a
for
loop, which is part of the control flow syntax that we’ll
. A
for
loop allows you to specify an initial condi‐
tion (25), an ending condition (less than 400), and an increment value (50). We use
one loop inside the other to accomplish this for both the x-axis and y-axis.
There are many ways we could have written this example. The way
we’ve written it, we’ve made the x and y coordinates the important
pieces of information: we explicitly specify where the circles will
start and how far apart they’ll be spaced. We could have
approached this problem from another direction: we could have
said what’s important is the number of circles we want (64), and let
the program figure out how to space them so that they fit on the
canvas. The reason we went with this solution is that it better
matches what we would have done if we had cut and pasted our
circle code 64 times and figured out the spacing ourselves.
Automating Repetitive Tasks | 11