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
1class Walker {2 constructor(xi, yi) {3 this.x = xi4 this.y = yi5 }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
1const h = 5002const w = 7003
4let walker5
6function setup() {7 createCanvas(w, h)8 background(220)9
10 walker = new Walker(w / 2, h / 2)11}12
13function draw() {14 walker.step()15}
Random Coloured Walkers
We can also create a whole bunch of random walkers with random colours like so:
1const h = 12002const w = 12003
4let walkers = []5
6function 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
15function draw() {16 walkers.forEach((w) => w.step())17}18
19class 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 25534 if (newC >= 254) return 035 else return newC36 }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
1const w = 600,2 h = 500,3 r = 504
5let position6let velocity7
8this.setup = () => {9 createCanvas(w, h)10
11 position = createVector(random(r, w - r), random(r, h - r))12 velocity = createVector(10, 10)13}14
15this.draw = () => {16 background(0)17
18 position.add(velocity)19
20 if (position.x <= r || position.x >= w - r) velocity.x *= -121 if (position.y <= r || position.y >= h - r) velocity.y *= -122
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