- Getting Started with p5.js book
- Chapter 4 Variables 4.5-4.13
- Part One: Iterative Pattern
- video 4.1:
while
andfor
(~14 min) - video 4.2: nested loops (~10 min)
- Tutorial: Recode Metaesquema by Hélio Oiticica
In this exercise we'll explore creating patterns as seen in textiles or wall papers. We will also apply randomness to get variety. You can think of patterns as frozen imprints of the animations techniques we have used so far.
To repeatedly execute statements we can use the while
conditional:
while (**test**) {
**statements**
}
Any number of statements will be executed while the test is true
. We must make sure the test is false
at some point otherwise the browser will lockup and we will have to close the page.
Drawing a shape across the canvas can be done concisely using a variable and the while
statement. In this sketch one row of a simple shape is drawn left to right on the canvas:
while (x < width) {
console.log('x='+x+' y='+y);
rect(x, y, 50, 50);
circle(x + 25, y + 25, 40);
x = x + 50;
}
Compare this sketch to the previous sketches that produce animations. You'll should note that there is no draw
function in this sketch. All drawing is done in the setup
function.
- modify the sketch to fill the canvas with the shape.
- hint: add code to modify the
y
variable and test it against the canvasheight
variable
- hint: add code to modify the
- modify the previous sketch to consolidate the drawing code into a user defined function
sketch - 4.1 pattern drawShape1
- modify the previous sketch to use randomness and your user defined function to create a variety of patterns
We can also repeatedly execute statements using the for
statement. The essential expressions that affect the loop are grouped together.
for (**initialize**; **test**; **change**) {
**statements**
}
The initialize code is executed once. While the test is true
the statements are executed, followed by the change code.
For example:
for (let x = 0; x < 5; x += 1) {
console.log('x='+x);
}
The variable x
will take on values 0, 1, 2, 3, 4.
Write your own for-loop that draws a repeating shape on one row of the canvas.
Fill the canvas with a pattern. Organize your shape into a user defined function and have it fill the canvas using for-loops.
sketch - 4.2 for-loop drawShape1
Add randomness to your pattern.
sketch - 4.2 for-loop random 2
sketch - 4.2 for-loop random 3
sketch - 4.2 for-loop random 4
Sketches from the Getting Started book.
You are invited to remix and combine them to further explore.
- Chapter 4 Variables
Ex_04_05 Do the Same
Ex_04_06 Use a for Loop
Ex_04_07 Flex Your for Loop’s
Ex_04_08 Fanning Out the Lines
Ex_04_09 Kinking the Lines
Ex_04_10 Embed for Loop
Ex_04_11 Rows and Columns
Ex_04_12 Pins and Lines
Ex_04_13 Halftone Dots
Ex_04_99 Robot 2: Variables
Ex_04_99 Robot 2: Variable func
Ex_04_99 Robot 2: func jiggle