p5.js

Introductory p5.js notes

Updated: 03 September 2023

Notes from p5.js and The Nature of Code

Random Walk

Using p5 we can create a random walker. With p5 we usually structure stuff using OOP, for example we will define a random walker with the ability to take a new step as well as render itself:

Walker.js

1
class Walker {
2
constructor(xi, yi) {
3
this.x = xi
4
this.y = yi
5
}
6
7
step() {
8
this.x += random(-2, 2)
9
this.y += random(-2, 2)
10
11
this.draw()
12
}
13
14
draw() {
15
stroke('red')
16
strokeWeight(2)
17
point(this.x, this.y)
18
}
19
}

We also need to create a walker instance and define the needed setup and draw functions for p5:

sketch.js

1
const h = 500
2
const w = 700
3
4
let walker
5
6
function setup() {
7
createCanvas(w, h)
8
background(220)
9
10
walker = new Walker(w / 2, h / 2)
11
}
12
13
function draw() {
14
walker.step()
15
}
Random Coloured Walkers

We can also create a whole bunch of random walkers with random colours like so:

1
const h = 1200
2
const w = 1200
3
4
let walkers = []
5
6
function setup() {
7
createCanvas(w, h)
8
background('red')
9
10
for (let step = 0; step < 500; step++) {
11
walkers.push(new Walker(width, height, 100))
12
}
13
}
14
15
function draw() {
16
walkers.forEach((w) => w.step())
17
}
18
19
class Walker {
20
constructor(w, h, b) {
21
this.x = random(b, w - b)
22
this.y = random(b, h - b)
23
24
this.c1 = random(0, 255)
25
this.c2 = random(0, 255)
26
this.c3 = random(0, 255)
27
}
28
29
step() {
30
function getC(c) {
31
const newC = c + random(-2, 2)
32
33
if (newC <= 1) return 255
34
if (newC >= 254) return 0
35
else return newC
36
}
37
38
this.c1 = getC(this.c1)
39
this.c2 = getC(this.c2)
40
this.c3 = getC(this.c3)
41
42
this.x += random(-2, 2)
43
this.y += random(-2, 2)
44
45
this.draw()
46
}
47
48
draw() {
49
stroke(this.c1, this.c2, this.c3)
50
strokeWeight(2)
51
point(this.x, this.y)
52
}
53
}

Vectors

p5 also contains a Vector Class, this is a class of functions that allows us to work with vectors as mathematical structures

We can create a bouncing ball animation by using two vectors, one for position and one for velocity we can apply some vector math to get the ball to bounce around the screen

1
const w = 600,
2
h = 500,
3
r = 50
4
5
let position
6
let velocity
7
8
this.setup = () => {
9
createCanvas(w, h)
10
11
position = createVector(random(r, w - r), random(r, h - r))
12
velocity = createVector(10, 10)
13
}
14
15
this.draw = () => {
16
background(0)
17
18
position.add(velocity)
19
20
if (position.x <= r || position.x >= w - r) velocity.x *= -1
21
if (position.y <= r || position.y >= h - r) velocity.y *= -1
22
23
fill('red')
24
noStroke()
25
ellipse(position.x, position.y, r * 2)
26
}

We cal also do something like the above using a 3D canvas