Published
Edited
Oct 1, 2019
4 stars
Insert cell
Insert cell
Insert cell
{
replay;
const context = DOM.context2d(width, width);
context.translate(width / 2, width / 2);
const margin = 200;

const struc = [new Particle(0, 0, 3, "black")];
let current = [];

for (let i = 0; i < 3000; ++i) {
current.push(
new Particle(
-width / 2 + margin / 2 + Math.random() * (width - margin),
-width / 2 + margin / 2 + Math.random() * (width - margin)
)
);
}

yield context.canvas;
while (true) {
await Promises.delay(10);
context.clearRect(-width / 2, -width / 2, width, width);

for (let i = 0; i < current.length; ++i) {
let c = current[i];
c.draw(context);
c.update();

if (c.stick(struc)) {
struc.push(c);
current.splice(i, 1);
// current.push(
// new Particle(
// -width / 2 + margin / 2 + Math.random() * (width - margin),
// -width / 2 + margin / 2 + Math.random() * (width - margin)
// )
// );
}
}

for (let p of struc) {
p.draw(context);
}
}
}
Insert cell
class Particle {
constructor(x, y, r = 3, c = "rgb(200, 200, 200)") {
this.pos = [x, y];
this.r = r;
this.color = c;
this.step = 6;
this.con = false;
}

update() {
const [x, y] = this.pos;
const { step } = this;
let [nextX, nextY] = [
x + Math.floor(-step + Math.random() * (2 * step + 1)),
y + Math.floor(-step + Math.random() * (2 * step + 1))
];

this.pos = [nextX, nextY];
}

stick(struc, context) {
for (let other of struc) {
const d = dist2D(other.pos, this.pos);
const target = other.r + this.r + 10;
if (d <= target) {
this.color = "rgb(100, 100, 100)";
this.con = other.pos;
return true;
}
}
}

draw(context) {
const [x, y] = this.pos;
const { color, r } = this;
context.beginPath();
context.fillStyle = color;
context.fillRect(x, y, r, r);
if (this.con) {
const pos = [x + r / 2, y + r / 2];
const [oX, oY] = this.con;
const otherPos = [oX + r / 2, oY + r / 2];
line(pos, otherPos, context, {
lineWidth: r * 0.5
});
}
}
}
Insert cell
import { circle, dist2D, line } from '@timhau/geometry'
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