Processing (36/381) : Structure
Processing (36/381) : Structure
————————————————————————————————————————————————————-
—————————————————————————————————————————————————————
—————————————————————————————————————————————————————
Structure:
setup()
int x = 0;
void setup() {
size(200, 200);
background(0);
noStroke();
fill(102);
}
void draw() {
rect(x, 10, 2, 80);
x = x + 1;
}
The setup() function is run once, when the program starts. It's used to define initial
enviroment properties such as screen size and to load media such as images and fonts as
the program starts. There can only be one setup() function for each program and it
shouldn't be called again after its initial execution.
If the sketch is a different dimension than the default, the size() function or
fullScreen() function must be the first line in setup().
Note: Variables declared within setup() are not accessible within other functions,
including draw().
—————————————————————————————————————————————————————
draw()
float yPos = 0.0;
1
Called directly after setup(), the draw() function continuously executes the lines of
code contained inside its block until the program is stopped or noLoop() is called. All
Processing programs update the screen at the end of draw(), never earlier.
To stop the code inside of draw() from running continuously, use noLoop(), redraw() and
loop(). If noLoop() is used to stop the code in draw() from running, then redraw() will
cause the code inside draw() to run a single time, and loop() will cause the code inside
draw() to resume running continuously.The number of times draw() executes in each second
may be controlled with the frameRate() function.
It is common to call background() near the beginning of the draw() loop to clear the
contents of the window. Since pixels drawn to the window are cumulative, omitting
background() may result in unintended results.
There can only be one draw() function for each sketch, and draw() must exist if you want
the code to run continuously.
—————————————————————————————————————————————————————
—————————————————————————————————————————————————————
Environment:
size()
size(200, 100);
background(153);
line(0, 0, width, height);
Defines the dimension of the display window width and height in units of pixels. In a
program that has the setup() function, the size() function must be the first line of
code inside setup(), and the setup() function must appear in the code tab with the same
name as your sketch folder.
The built-in variables width and height are set by the parameters passed to this
function. For example, running size(640, 480) will assign 640 to the width variable and
480 to the height variable. If size() is not used, the window will be given a default
size of 100 x 100 pixels.The size() function can only be used once inside a sketch, and
it cannot be used for resizing.
The minimum width and height is around 100 pixels in each direction.
The renderer parameter selects which rendering engine to use. For example, if you will
be drawing 3D shapes, use P3D. In addition to the default renderer, other renderers are
P2D (Processing 2D), P3D (Processing 3D), FX2D (JavaFX 2D), PDF and SVG.
As of Processing 3.0, to use variables as the parameters to size() function, place the
size() function within the settings() function (instead of setup()).
size(width, height)
size(width, height, renderer)
2
—————————————————————————————————————————————————————
—————————————————————————————————————————————————————
2D Primitives:
point()
point(30, 20);
Draws a point, a coordinate in space at the dimension of one pixel. The first parameter
is the horizontal value for the point, the second value is the vertical value for the
point, and the optional third value is the depth value. Drawing this shape in 3D with
the z parameter requires the P3D parameter in combination with size() as shown in the
above example.
—————————————————————————————————————————————————————
line()
Draws a line (a direct path between two points) to the screen. The version of line()
with four parameters draws the line in 2D. To color a line, use the stroke() function. A
line cannot be filled, therefore the fill() function will not affect the color of a
line. 2D lines are drawn with a width of one pixel by default, but this can be changed
with the strokeWeight() function. The version with six parameters allows the line to be
placed anywhere within XYZ space. Drawing this shape in 3D with the z parameter requires
the P3D parameter in combination with size() as shown in the above example.
3
—————————————————————————————————————————————————————
rect()
Draws a rectangle to the screen. A rectangle is a four-sided shape with every angle at
ninety degrees. By default, the first two parameters set the location of the upper-left
corner, the third sets the width, and the fourth sets the height. The way these
parameters are interpreted, however, may be changed with the rectMode() function.
To draw a rounded rectangle, add a fifth parameter, which is used as the radius value
for all four corners.
To use a different radius value for each corner, include eight parameters. When using
eight parameters, the latter four set the radius of the arc at each corner separately,
starting with the top-left corner and moving clockwise around the rectangle.
—————————————————————————————————————————————————————
circle()
Draws a circle to the screen. By default, the first two parameters set the
location of the center, and the third sets the shape's width and height. The
origin may be changed with the ellipseMode() function.
4
—————————————————————————————————————————————————————
—————————————————————————————————————————————————————
Color:
background()
background(51);
The background() function sets the color used for the background of the Processing
window. The default background is light gray. This function is typically used within
draw() to clear the display window at the beginning of each frame, but it can be used
inside setup() to set the background on the first frame of animation or if the backgound
need only be set once.
An image can also be used as the background for a sketch, although the image's width and
height must match that of the sketch window. Images used with background() will ignore
the current tint() setting. To resize an image to the size of the sketch window, use
image.resize(width, height).
It is not possible to use the transparency alpha parameter with background colors on the
main drawing surface. It can only be used along with a PGraphics object and
createGraphics().
background(rgb)
background(rgb, alpha)
background(gray)
background(gray, alpha)
background(v1, v2, v3)
background(v1, v2, v3, alpha)
background(image)
—————————————————————————————————————————————————————
fill()
fill(153);
rect(30, 20, 55, 55);
5
Sets the color used to fill shapes. For example, if you run fill(204, 102, 0), all
subsequent shapes will be filled with orange. This color is either specified in terms of
the RGB or HSB color depending on the current colorMode(). The default color space is
RGB, with each value in the range from 0 to 255.
When using hexadecimal notation to specify a color, use "#" or "0x" before the values
(e.g., #CCFFAA or 0xFFCCFFAA). The # syntax uses six digits to specify a color (just as
colors are typically specified in HTML and CSS). When using the hexadecimal notation
starting with "0x", the hexadecimal value must be specified with eight characters; the
first two characters define the alpha component, and the remainder define the red,
green, and blue components.
The value for the "gray" parameter must be less than or equal to the current maximum
value as specified by colorMode(). The default maximum value is 255.
fill(rgb)
fill(rgb, alpha)
fill(gray)
fill(gray, alpha)
fill(v1, v2, v3)
fill(v1, v2, v3, alpha)
—————————————————————————————————————————————————————
stroke()
stroke(153);
rect(30, 20, 55, 55);
Sets the color used to draw lines and borders around shapes. This color is either
specified in terms of the RGB or HSB color depending on the current colorMode().
When using hexadecimal notation to specify a color, use "#" or "0x" before the values
(e.g., #CCFFAA or 0xFFCCFFAA). The # syntax uses six digits to specify a color. When
using the hexadecimal notation starting with "0x", the hexadecimal value must be
specified with eight characters; the first two characters define the alpha component,
and the remainder define red, green, and blue. The value for the gray parameter must be
less than or equal to the current maximum value as specified by colorMode(). The default
maximum value is 255.
stroke(rgb)
stroke(rgb, alpha)
stroke(gray)
stroke(gray, alpha)
stroke(v1, v2, v3)
stroke(v1, v2, v3, alpha)
6
—————————————————————————————————————————————————————
—————————————————————————————————————————————————————
input:
mouseX
void draw() {
background(204);
line(mouseX, 20, mouseX, 80);
}
The system variable mouseX always contains the horizontal coordinate of the mouse.
Note that Processing can only track the mouse position when the pointer is over the
current window. The default value of mouseX is 0, so 0 will be returned until the mouse
moves in front of the sketch window. (This typically happens when a sketch is first
run.) Once the mouse moves away from the window, mouseX will continue to report its most
recent position.
—————————————————————————————————————————————————————
mouseY
void draw() {
background(204);
line(20, mouseY, 80, mouseY);
}
The system variable mouseY always contains the current vertical coordinate of the mouse.
Note that Processing can only track the mouse position when the pointer is over the
current window. The default value of mouseY is 0, so 0 will be returned until the mouse
moves in front of the sketch window. (This typically happens when a sketch is first
run.) Once the mouse moves away from the window, mouseY will continue to report its most
recent position.
—————————————————————————————————————————————————————
pmouseX
// Move the mouse quickly to see the difference
// between the current and previous position
void draw() {
background(204);
line(mouseX, 20, pmouseX, 80);
println(mouseX + " : " + pmouseX);
}
7
The system variable pmouseX always contains the horizontal position of the mouse in the
frame previous to the current frame.
You may find that pmouseX and pmouseY have different values when referenced inside of
draw() and inside of mouse events like mousePressed() and mouseMoved(). Inside draw(),
pmouseX and pmouseY update only once per frame (once per trip through the draw() loop).
But inside mouse events, they update each time the event is called. If these values
weren't updated immediately during mouse events, then the mouse position would be read
only once per frame, resulting in slight delays and choppy interaction. If the mouse
variables were always updated multiple times per frame, then something like
line(pmouseX, pmouseY, mouseX, mouseY) inside draw() would have lots of gaps, because
pmouseX may have changed several times in between the calls to line().
If you want values relative to the previous frame, use pmouseX and pmouseY inside
draw(). If you want continuous response, use pmouseX and pmouseY inside the mouse event
functions.
—————————————————————————————————————————————————————
pmouseY
The system variable pmouseY always contains the vertical position of the mouse in the
frame previous to the current frame.
For more detail on how pmouseY is updated inside of mouse events and draw(), see the
reference for pmouseX.
—————————————————————————————————————————————————————
mousePressed()
// Click within the image to change
// the value of the rectangle
int value = 0;
void draw() {
fill(value);
rect(25, 25, 50, 50);
}
void mousePressed() {
if (value == 0) {
value = 255;
} else {
value = 0;
}
8
}
The mousePressed() function is called once after every time a mouse button is pressed.
The mouseButton variable can be used to determine which button has been pressed.
Mouse and keyboard events only work when a program has draw(). Without draw(), the code
is only run once and then stops listening for events.
—————————————————————————————————————————————————————
—————————————————————————————————————————————————————
keyboard:
keyPressed()
// Click on the image to give it focus,
// and then press any key.
int value = 0;
void draw() {
fill(value);
rect(25, 25, 50, 50);
}
void keyPressed() {
if (value == 0) {
value = 255;
} else {
value = 0;
}
}
The keyPressed() function is called once every time a key is pressed. The key that was
pressed is stored in the key variable.
Because of how operating systems handle key repeats, holding down a key may cause
multiple calls to keyPressed(). The rate of repeat is set by the operating system, and
may be configured differently on each computer.
Mouse and keyboard events only work when a program has draw(). Without draw(), the code
is only run once and then stops listening for events.
9
—————————————————————————————————————————————————————
—————————————————————————————————————————————————————
Conditionals:
if
Allows the program to make a decision about which code to execute. If the test evaluates
to true, the statements enclosed within the block are executed and if the test evaluates
to false the statements are not executed.
—————————————————————————————————————————————————————
else
10
for (int i = 5; i < 95; i += 5) {
if (i < 35) {
line(30, i, 80, i);
} else {
line(20, i, 90, i);
}
}
Extends the if structure allowing the program to choose between two or more blocks of
code. It specifies a block of code to execute when the expression in if is false.
—————————————————————————————————————————————————————
—————————————————————————————————————————————————————
Relational Operators:
!= (inequality)
int a = 22;
int b = 23;
if (a != b) {
println("variable a is not equal to variable b”);
}
—————————————————————————————————————————————————————
11
> (greater than)
int a = 5;
int b = 13;
if (b > a) {
println("variable b is larger the variable a");
}
Tests if the value on the left is larger than the value on the right.
—————————————————————————————————————————————————————
>= (greater than or equal to)
int a = 23;
int b = 23;
if (a >= b) {
println("variable a is greater or equal to variable b ")
}
Tests if the value on the left is larger than the value on the right or if the values are
equivalent.
—————————————————————————————————————————————————————
< (less than)
int a = 22;
int b = 23;
if (a < b) {
println("variable a is less then variable b ");
}
Tests if the value on the left is smaller than the value on the right.
—————————————————————————————————————————————————————
<= (less than or equal to)
int a = 22;
int b = 23;
if (a <= b) {
println("variable a is less or equal to variable b ");
}
Tests if the value on the left is less than the value on the right or if the values are
equivalent.
—————————————————————————————————————————————————————
== (equality)
int a = 23;
int b = 23;
if (a == b) {
println("variables a and b are equal");
}
Determines if two values are equivalent. The equality operator is different from the
assignment operator.
12
—————————————————————————————————————————————————————
—————————————————————————————————————————————————————
Data:
int
int a; // Declare variable 'a' of type int
a = 23; // Assign 'a' the value 23
int b = -256; // Declare variable 'b' and assign it the value -256
int c = a + b; // Declare variable 'c' and assign it the sum of 'a' and ‘b'
Datatype for integers, numbers without a decimal point. Integers can be as large as
2,147,483,647 and as low as -2,147,483,648. They are stored as 32 bits of information.
The first time a variable is written, it must be declared with a statement expressing its
datatype. Subsequent uses of this variable must not reference the datatype because
Processing will think the variable is being declared again.
—————————————————————————————————————————————————————
float
float f1 = 0.0;
for (int i = 0 ; i < 100000; i++) {
f1 = f1 + 0.0001; // Bad idea! See below.
}
println(f1);
float f2 = 0.0;
for (int i = 0; i < 100000; i++) {
// The variable 'f2' will work better here, less affected by rounding
f2 = i / 1000.0; // Count by thousandths
}
println(f2);
Data type for floating-point numbers, e.g. numbers that have a decimal point.
Floats are not precise, so adding small values (such as 0.0001) may not always increment
precisely due to rounding errors. If you want to increment a value in small intervals,
use an int, and divide by a float value before using it. (See the second example above.)
Processing supports the double datatype from Java as well. However, none of the
Processing functions use double values, which use more memory and are typically overkill
for most work created in Processing. We do not plan to add support for double values, as
doing so would require increasing the number of API functions significantly.
13
—————————————————————————————————————————————————————
boolean
boolean a = false;
if (!a) {
rect(30, 20, 50, 50);
}
a = true;
if (a) {
line(20, 10, 90, 80);
line(20, 80, 90, 10);
}
Datatype for the Boolean values true and false. It is common to use boolean values with
control statements to determine the flow of a program. The first time a variable is
written, it must be declared with a statement expressing its datatype.
14
—————————————————————————————————————————————————————
—————————————————————————————————————————————————————
Logical Operators:
&& (logical AND)
Compares two expressions and returns true only if both evaluate to true. Returns false
if one or both evaluate to false. The following list shows all possible combinations:
—————————————————————————————————————————————————————
|| (logical OR)
15
—————————————————————————————————————————————————————
! (logical NOT)
boolean a = false;
if (!a) {
rect(30, 20, 50, 50);
}
if (a) {
line(20, 10, 90, 80);
line(20, 80, 90, 10);
}
boolean a = true;
if (!a) {
rect(30, 20, 50, 50);
}
if (a) {
line(20, 10, 90, 80);
line(20, 80, 90, 10);
}
Inverts the Boolean value of an expression. Returns true if the expression is false and
returns false if the expression is true. If the expression (a>b) evaluates to true, then
!(a>b) evaluates to false.
16
—————————————————————————————————————————————————————
—————————————————————————————————————————————————————
Random:
random()
for (int i = 0; i < 100; i++) {
float r = random(50);
stroke(r*5);
line(50, i, 50+r, i);
}
Generates random numbers. Each time the random() function is called, it returns an
unexpected value within the specified range. If only one parameter is passed to the
function, it will return a float between zero and the value of the high parameter. For
example, random(5) returns values between 0 and 5 (starting at zero, and up to, but not
including, 5).
If two parameters are specified, the function will return a float with a value between
the two values. For example, random(-5, 10.2) returns values starting at -5 and up to
(but not including) 10.2. To convert a floating-point random number to an integer, use
the int() function.
17
—————————————————————————————————————————————————————
—————————————————————————————————————————————————————
Output:
println()
String s = "The size is ";
int w = 1920;
int h = 1080;
println(s);
println(w, "x", h);
print("begin- ");
float f = 0.3;
int i = 1024;
print("f is " + f + " and i is " + 1024);
String s = " -end";
println(s);
The println() function writes to the console area, the black rectangle at the bottom of
the Processing environment. This function is often helpful for looking at the data a
program is producing. Each call to this function creates a new line of output. More than
one parameter can be passed into the function by separating them with commas.
Alternatively, individual elements can be separated with quotes ("") and joined with the
addition operator (+).
Before Processing 2.1, println() was used to write array data to the console. Now, use
printArray() to write array data to the console.
Note that the console is relatively slow. It works well for occasional messages, but
does not support high-speed, real-time output (such as at 60 frames per second). It
should also be noted, that a println() within a for loop can sometimes lock up the
program, and cause the sketch to freeze.
18
—————————————————————————————————————————————————————
—————————————————————————————————————————————————————
Atributes:
strokeWeight()
strokeWeight(1); // Default
line(20, 20, 80, 20);
strokeWeight(4); // Thicker
line(20, 40, 80, 40);
strokeWeight(10); // Beastly
line(20, 70, 80, 70);
Sets the width of the stroke used for lines, points, and the border around shapes. All
widths are set in units of pixels.
19
—————————————————————————————————————————————————————
—————————————————————————————————————————————————————
Iteration:
while
int i = 0;
while (i < 80) {
line(30, i, 80, i);
i = i + 5;
}
This function can be dangerous because the code inside the while loop will not finish
until the expression inside while becomes false. It will lock out all other code from
running (e.g., mouse and keyboard events will not be updated). Be careful — if used
incorrectly, this can lock up your code (and sometimes even the Processing environment
itself).
—————————————————————————————————————————————————————
for
20
for (int i = 0; i < 40; i = i+1) {
line(30, i, 80, i);
}
int[] nums = { 5, 4, 3, 2, 1 };
21
Controls a sequence of repetitions. A basic for structure has three parts: init, test,
and update. Each part must be separated by a semicolon (;). The loop continues until the
test evaluates to false. When a for structure is executed, the following sequence of
events occurs:
In the first example above, the for structure is executed 40 times. In the init
statement, the value i is created and set to zero. i is less than 40, so the test
evaluates as true. At the end of each loop, i is incremented by one. On the 41st
execution, the test is evaluated as false, because i is then equal to 40, so i < 40 is
no longer true. Thus, the loop exits.
A second type of for structure makes it easier to iterate over each element of an array.
The last example above shows how it works. Within the parentheses, first define the
datatype of the array, then define a variable name. This variable name will be assigned
to each element of the array in turn as the for moves through the entire array. Finally,
after the colon, define the array name to be used.
22
—————————————————————————————————————————————————————
—————————————————————————————————————————————————————
Calculation:
dist()
// Sets the background gray value based on the distance
// of the mouse from the center of the screen
void draw() {
noStroke();
float d = dist(width/2, height/2, mouseX, mouseY);
float maxDist = dist(0, 0, width/2, height/2);
float gray = map(d, 0, maxDist, 0, 255);
fill(gray);
rect(0, 0, width, height);
}
23