html,
body {
margin: 0;
padding: 0;
}
canvas {
display: block;
}
// radius -> the distance between the body and the center of the page. Its variation it's what produces the drawings
// angle -> an initial value for the angle, it will increment indefinitely
// velocity -> the rotational velocity of the body, the more velocity it has, the more the angle will increment, producing more curved lines
// alpha, beta -> constants values defined randomly at construction. It defines the ratio at which the radius varies according to the following function: alpha * cos(beta * theta)
class Body {
constructor(radius, angle, velocity) {
this.radius = radius;
this.angle = angle;
this.velocity = velocity;
this.alpha = random(20);
this.beta = random(40);
this.clr = color(random(255), 0, random(255));
this.history = [];
}
update() {
this.angle += this.velocity;
this.radius += this.alpha * cos(this.beta * this.angle);
}
drawTrace() {
for (let i = 1; i < this.history.length; i++) {
let previousPoint = this.history[i - 1];
let currentPoint = this.history[i];
stroke(this.clr);
line(previousPoint.x, previousPoint.y, currentPoint.x, currentPoint.y);
}
}
display() {
let x = this.radius * cos(this.angle);
let y = this.radius * sin(this.angle);
this.history.push({ x, y });
if (this.history.length > 400) this.history.splice(0, 1);
stroke(0);
line(0, 0, x, y);
fill(this.clr);
circle(x, y, 24);
this.drawTrace();
}
}
let bodies;
function setup() {
createCanvas(windowWidth, windowHeight);
createBodies();
}
function draw() {
background(255);
// Translate the cartesian plane so that the origin is in the center of the page
translate(width / 2, height / 2);
noStroke();
fill(0);
// Make a circle in the center of the page for reference
circle(0, 0, 12);
bodies.forEach((body) => {
body.display();
body.update();
});
}
function keyPressed() {
if (keyCode === ENTER) {
createBodies();
}
}
function createBodies() {
bodies = [];
for (let i = 0; i < 5; i++) {
let body = new Body(random(100), 0, random(0.5));
bodies.push(body);
}
}
This Pen doesn't use any external CSS resources.