Published
Edited
Jan 19, 2021
1 fork
4 stars
Also listed in…
p5
Insert cell
md`# P5 js Sketch learnings`
Insert cell
import {p5} from "@tmcw/p5";

Insert cell
Insert cell
p5(sketch => {
let snowflakes = []; // array to hold snowflake objects

sketch.setup = function() {
sketch.createCanvas(400, 600);
sketch.fill(240);
sketch.noStroke();
}

sketch.draw = function() {
sketch.background('brown');
let t = sketch.frameCount / 60; // update time

// create a random number of snowflakes each frame
for (let i = 0; i < sketch.random(5); i++) {
snowflakes.push(new snowflake()); // append snowflake object
}

// loop through snowflakes with a for..of loop
for (let flake of snowflakes) {
flake.update(t); // update snowflake position
flake.display(); // draw snowflake
}
}

// snowflake class
function snowflake() {
// initialize coordinates
this.posX = 0;
this.posY = sketch.random(-50, 0);
this.initialangle = sketch.random(0, 2 * sketch.PI);
this.size = sketch.random(2, 5);

// radius of snowflake spiral
// chosen so the snowflakes are uniformly spread out in area
this.radius = sketch.sqrt(sketch.random(sketch.pow(width / 2, 2)));

this.update = function(time) {
// x position follows a circle
let w = 0.6; // angular speed
let angle = w * time + this.initialangle;
this.posX = width / 2 + this.radius * sketch.sin(angle);

// different size snowflakes fall at slightly different y speeds
this.posY += sketch.pow(this.size, 0.5);

// delete snowflake if past end of screen
if (this.posY > sketch.height) {
let index = snowflakes.indexOf(this);
snowflakes.splice(index, 1);
}
};

this.display = function() {
sketch.ellipse(this.posX, this.posY, this.size);
};
}

})
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more