Setup&Draw in Processing#
Until now, we were just drawing a single image once. Processing has a facility to run your code continually, that we're going to make heavy use of: setup()
and draw()
!
How Do We Use Setup?#
This is a tiny bit of boilerplate1 code that you can just copy over to your processing window. Whatever is in the middle will get run exactly once at the beginning of your program. setup()
and draw()
(and a few more) are special, because when processing finds these, it will automatically just use them.
We call that stuff in the middle a block of code. It starts at the curly brace {
and ends at the other curly brace }
.
How Do We Use Draw?#
draw()
looks almost exactly the same. The only real difference is, how processing runs the two. It is a little bit of a misnomer, because we will do a whole lot more than just draw things in it.
Full Example#
void setup() {
size(200, 400);
background(0, 0, 0);
stroke(255, 0, 0);
}
void draw() {
circle(100, 200, 25);
}
While that looks a lot more complicated then what we've been doing all along, this unlocks a heap of possibilities! Instead of drawing things just once, we actually get frames (as in movie frames) and we will learn to change them over time.
You will also have noticed that things in the setup()
and draw()
blocks of code are indented slightly. This is a common convention that helps you visually remember that these are part of setup()
and draw()
, and that they don't just run on their own.
But… Sequence of Commands#
I used to emphasize heavily how code is run from top to bottom. This is still the case, but we need to amend that rule a little bit. Within setup()
and within draw()
we're still following the sequence of commands. But if I were to switch the two functions around, setup()
would still run first even though it comes after draw()
. Also draw()
runs multiple times.
void draw() {
circle(100, 200, 25);
}
void setup() {
size(200, 400);
background(0, 0, 0);
stroke(255, 0, 0);
}
Relevant excerpt from Learning Processing#
(the section starts at 1:04:39 and runs through 1:13:05, the video should start and stop on these automatically.)
-
We call readily prepared templates or endless lines of code that you need to just copy and paste "boilerplate". This will come up every once in a while. While the term itself is not terribly important, it's probably good to know. ↩