Published
Edited
Feb 16, 2020
Insert cell
Insert cell
canvas = {
const context = DOM.context2d(width, height);

const particles = new Array(n);
for (let i = 0; i < n; ++i) {
particles[i] = {
x: Math.random() * width,
y: Math.random() * height,
vx: 0,
vy: 0,
color: color()
};
}
function color() {
var s = "0123456789ABCDEF";
var c = "#";
for (var i = 0; i < 6; i++) {
c += s[Math.ceil(Math.random() * 15)]
}
return c
}

let fade = 0;
context.fillRect(0, 0, width, height);
while (true) {
context.save();
if (fade++ > 3) {
context.globalAlpha = .05;
context.fillStyle = 'black';
context.fillRect(0, 0, width, height);
fade = 0;
} else {
context.globalAlpha = 1;
}
for (let i = 0; i < n; ++i) {
const p = particles[i];
p.x += p.vx;
if (p.x < -maxDistance) p.x += width + maxDistance * 2;
else if (p.x > width + maxDistance) p.x -= width + maxDistance * 2;
p.y += p.vy;
if (p.y < -maxDistance) p.y += height + maxDistance * 2;
else if (p.y > height + maxDistance) p.y -= height + maxDistance * 2;
p.vx += 0.2 * (Math.random() - .5) - 0.01 * p.vx;
p.vy += 0.2 * (Math.random() - .5) - 0.01 * p.vy;
context.beginPath();
context.fillStyle = p.color;
context.arc(p.x, p.y, radius, 0, 2 * Math.PI);
context.fill();
}

context.restore();
yield context.canvas;
}
}
Insert cell
n = 100
Insert cell
height = 600
Insert cell
radius = 5
Insert cell
minDistance = 40
Insert cell
maxDistance = 60
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more