Special Variables and Conditional Statements
This chapter introduces special variables that are useful for interactive programs and for placing shapes. You will also learn complex programs using conditional statements.
Data Types
In Chapter 2, we used variables to store numbers, but other types of information can be stored in variables of different types. The type of data is automatically determined by the computer at the time the value is assigned to the variable. Also, the arguments of functions and calculations must follow the defined type. The computer automatically converts the type when possible, otherwise it will raise an error.
Type | Description | Declaration / Usage |
---|---|---|
Number | Integer and Decimals |
|
String | Strings are enclosed in double-quotation marks " . |
|
Boolean | Can be either true or false value. |
|
Color | Can store color information and be used instead of three numbers in fill() etc. |
|
Draw Strings
Strings can also be drawn on the screen as images.
Here are two uses of the text()
function.
When you give a string and the coordinate of the upper left corner as an argument, the string is displayed in a line.
The size of the string must be predefined with the textSize()
function.
textSize(32);
text('word', 10, 30);
fill(0, 102, 153);
text('word', 10, 60);
fill(0, 102, 153, 51);
text('word', 10, 90);
In the above example,
fill
is given 4 arguments. In addition to the text color, the last argument specifies opaacity:fill(r, g, b, opacity)
. Opacity is also called alpha, and by setting this number, you can make the color behind the text transparent. alpha = 0 is completely transparent (the color is not visible at all and the background is transparent), alpha = 255 is completely opaque (only its own color is visible and it covers the background), and values in between are semitransparent.
When a string and the two coordinates of the upper left and lower right are given as arguments, the text size and line breaks are automatically determined to fit within the frame.
let s = 'The quick brown fox jumped over the lazy dog.';
fill(50);
text(s, 10, 10, 70, 80); // Text wraps within text box
System Variables
In addition to the variables you create yourself, p5.js provides other useful variables. The table below lists some of the most common ones. There are more system variables, and you can look up explanations with sample programs from the official website.
Variable | Type | Meaning |
---|---|---|
width | Number | Width of the drawing canvas |
height | Number | Height of the drawing canvas |
windowWidth | Number | Width of the inner window |
windowHeight | Number | Height of the inner window |
frameCount | Number | Number of frames that have been displayed since the program started |
mouseX | Number | Current horizontal position of the mouse |
mouseY | Number | Current vertical position of the mouse |
pmouseX | Number | Horizontal position of the mouse in the previous frame |
pmouseY | Number | Vertical position of the mouse in the previous frame |
mouseIsPressed | Boolean | Whether any mouse button is pressed |
mouseButton | Number | Which button is pressed ( takes one of LEFT / CENTER / RIGHT ) |
keyIsPressed | Boolean | Whether any key is pressed |
key | String | Last character key pressed |
keyCode | Number | Last key pressed including special keys (Visit https://keycode.info/ to find the name and number of the key) |
First of all, you should learn the width
, height
, mouseX
, and mouseY
.
These allow you to size the shape to fit the screen size and draw the shape at the mouse cursor position.
function setup(){
createCanvas(windowWidth, windowHeight); // Make the entire drawing area the canvas
}
function draw() {
background(180); // Fill every frame with background color
rect(width/4, height/4, width/2, height/2); // Draw a rectangle in the center of the screen, half the size of the screen
ellipse(mouseX, mouseY, 20, 20); // Draw a circle at the mouse cursor
}
Conditional Statement
In p5.js, you can use conditional statements to branch the program according to a complex logic. The following program divides the process into two blocks based on the cursor position to change the color of the circle.
function setup() {
createCanvas(windowWidth, windowHeight);
}
function draw() {
background(255);
line(width/2, 0, width/2, height);
if(mouseX < width/2){
// cases when the cursor is on the left half of the screen
fill(255, 80, 80); // 赤
circle(mouseX, mouseY, 40);
}
else{
// the other cases
fill(48, 255, 255); // light blue
circle(mouseX, mouseY, 40);
}
}
if statement requires a conditional expression and block(s) in which you write the process. The if block is executed when the conditional expression is true. Otherwise, the else block will run.
Conditional expressions are used to determine whether something is true or false. In addition to variables of the true/false type, you can define complex conditions using the following operations
Operator | Meaning | Example |
---|---|---|
== |
Both sides are equal | if( x == 10 ) |
!= |
Both sides are not equal | if( x == 10 ) |
> |
Left side is greater than right side | if( x == 10 ) |
>= |
Left side is equal to or greater than right side | if( x == 10 ) |
< |
Right side is greater than the left side | if( x == 10 ) |
<= |
Right side is equal to or greater than the left side | if( x == 10 ) |
&& |
Conjunction. Left side and right side | if( 0<=x && x<100 ) , x is equal to or greater than 0 and less than 100 |
|| | Disjunction. Left side or right side | if( x<0 ||100<x ) , x is less than 0 or greater than 100 |
! |
Negation. Not something. | if( !(x<=5) ) , x is not less than 5 |
Branching Patterns
If there is no process to execute if the condition is false, the else block can be omitted.
[ else omitted ]
Multiple branching is also possible by following else
with a further if
statement.
[ many branches ]
function setup() {
createCanvas(windowWidth, windowHeight);
background(255);
}
function draw() {
for(let i=0; i<width/10; i++){
// Set the color by 3 branches.
// i%3 means the remainder of i divided by 3
if(i%3 == 0){
stroke(255, 0, 0); // red
}
else if(i%3 == 1){
stroke(0, 255, 0); // green
}
else{
stroke(0, 0, 255); // blue
}
line(i*10, 0, i*10, height);
}
}
Use
stroke(color)
to specify the color of aline
or the outline of arect
(Iteration and Color Representation).
Exercises
Exercise 1
Arrange the shapes equally spaced across the screen using the system variables windowWidth
and windowHeight
and the for statement.
Calculate the spacing of the shapes from the width of the screen.
Exercise 2
Use the program created in Exercise 1.
In the for loop, use the conditional statements if, else
and the remainder operation %
to change the color of the shapes regularly.
Start by changing the color horizontally or vertically, then move on to more complex color changes.