Published
Edited
Aug 4, 2020
Insert cell
Insert cell
Insert cell
{
replay;
const context = DOM.context2d(width, width);
context.translate(width / 2, width / 2);

const points = [];
let t = 0;
const n = 200;
while (t < 1500) {
if (points.length < n && t % 5 === 0) {
const x = 0;
const y = 0;

const p = new Point(x, y, points.length);
points.push(p);
}
if (points.length === n) {
for (const point of points) {
point.final();
}
}

await Promises.delay(10);
context.clearRect(-width / 2, -width / 2, width, width);

for (let i = 0; i < points.length; ++i) {
points[i].move();
}

const delaunay = new d3.Delaunay(
points.reduce((acc, p) => [...p.pos, ...acc], [])
);
const voronoi = delaunay.voronoi([-width / 2, -width / 2, width, width]);

context.beginPath();
context.strokeStyle = "rgba(10,10,10,1)";
voronoi.render(context);
context.stroke();

context.beginPath();
delaunay.renderPoints(context, 1.5);
context.fill();

++t;
yield context.canvas;
}
}
Insert cell
class Point {
constructor(x, y, i) {
this.index = i;
this.isFinal = false;
const rowSize = 15;
const off = width / (rowSize + 1);
const row = Math.floor(i / rowSize);
this.finalPos = [
-width / 2 + off + (-1) ** row * (rowSize * 2) + (i % rowSize) * off,
-width / 2 + off + row * off
];
this.pos = [x, y];
this.vel = [-1 + Math.random() * 2, -1 + Math.random() * 2];
this.t = 0;
}

final() {
this.isFinal = true;
}

move() {
const { finalPos, isFinal, t } = this;

const [x, y] = this.pos;

if (!isFinal) {
const [vx, vy] = this.vel;
const [nx, ny] = [x + vx, y + vy];
if (nx <= -width / 2 || nx > width / 2) {
this.vel[0] *= -1;
}
if (ny <= -width / 2 || ny > width / 2) {
this.vel[1] *= -1;
}

this.pos = [nx, ny];
} else {
if (t < 1) {
const [fx, fy] = finalPos;
const [nx, ny] = [x + t * (fx - x), y + t * (fy - y)];
this.pos = [nx, ny];
this.t += 0.00005;
}
}
}
}
Insert cell
Insert cell
Insert cell
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