Published
Edited
May 27, 2020
Insert cell
Insert cell
animation = {
const height = 300;
const min = 0;
const max = 100;
const max2 = Math.pow(max, 2);
const context = DOM.context2d(width, height);
const canvas = context.canvas;

const n = 100;
const particles = new Array(n);
for (let i = 0; i < n; ++i) {
particles[i] = {
x: (Math.random() * (width + max * 2)) - max,
y: (Math.random() * (height + max * 2)) - max,
vx: 0,
vy: 0
};
}

while (true) {
for (let i = 0; i < n; ++i) {
const p = particles[i];
p.x += p.vx;
if (p.x < -max) p.x += width + max;
else if (p.x > width + max) p.x -= width + max;
p.y += p.vy;
if (p.y < -max) p.y += height + max;
else if (p.y > height + max) p.y -= height + max;
p.vx += mutable speed * (Math.random() - .5) - 0.01 * p.vx;
p.vy += mutable speed * (Math.random() - .5) - 0.01 * p.vy;
}

for (let i = 0; i < n; ++i) {
for (let j = i + 1; j < n; ++j) {
const pi = particles[i];
const pj = particles[j];
const dist = Math.pow(pi.x - pj.x, 2) + Math.pow(pi.y - pj.y, 2);
if (dist < max2) {
context.beginPath();
context.strokeStyle = `hsl(0,0%,${100 - (((max2 - dist) / max2) * 25)}%)`;
context.moveTo(pi.x, pi.y);
context.lineTo(pj.x, pj.y);
context.stroke();
}
}
}

yield canvas;
}
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
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