Public
Edited
Aug 2, 2023
Insert cell
Insert cell
Insert cell
// display the p5 container
display = {
let el = document.createElement("div");
el.id = container.id;
el.style.width = `${container.width}px`;
el.style.height = `${container.height}px`;
return el;
}
Insert cell
sketch = function (s) {
// set global vars here
const tau = 2 * Math.PI;
const n = 25; // number of particles

let particles = d3.range(n).map(() => ({
// pos: [Math.random() * container.width, Math.random() * container.height],
pos: [container.width / 3, container.height / 3],
v: [Math.random() * 10 - 5, Math.random() * 10 - 5]
}));

s.setup = function () {
s.createCanvas(container.width, container.height);

s.noStroke();
};

s.draw = function () {
// reset background
s.background("#eee");
switch (boundary) {
case "square":
s.fill("#fff");
s.rect(10, 10, container.width - 20, container.height - 20);
break;
case "circle":
s.fill("#fff");
s.circle(
container.width / 2,
container.height / 2,
Math.min(container.height, container.width) - 20
);
break;
}

particles.forEach((d) => {
// draw circle at new position
s.fill("blue");
s.circle(d.pos[0], d.pos[1], 5);

// update positions for next iteration
d.pos[0] += d.v[0];
d.pos[1] += d.v[1];

switch (boundary) {
case "square":
d.v[0] =
d.pos[0] < 10
? -d.v[0]
: d.pos[0] > container.width - 10
? -d.v[0]
: d.v[0];
d.v[1] =
d.pos[1] < 10
? -d.v[1]
: d.pos[1] > container.height - 10
? -d.v[1]
: d.v[1];
break;
case "circle":
// circle radius:
let r = (Math.min(container.height, container.width) - 20) / 2;
if (
Math.sqrt(
Math.pow(d.pos[0] - container.width / 2, 2) +
Math.pow(d.pos[1] - container.height / 2, 2)
) > r
) {
d.v[0] = -d.v[0];
d.v[1] = -d.v[1];
}
break;
}
});
};
}
Insert cell
container = ({ width: 500, height: 500, id: "p5-container" })
Insert cell
myP5 = {
// Resets div container
display.innerHTML = "";
// Reinstantiate the p5 with the sketch
return new p5(sketch, display);
}
Insert cell
p5 = require("p5")
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