Published
Edited
Feb 9, 2019
1 star
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
field = {
reset;
text;
const field = new Uint8Array(width * height);

const ctx = DOM.context2d(width, height, 1);
ctx.font = "100px serif";
ctx.textAlign = "center";
ctx.fillText(text, width / 2, height / 2);
const { data } = ctx.getImageData(0, 0, width, height);
for (let i = 0; i < data.length; i += 4) {
if (data[i + 3] > 0) {
field[i / 4] = 1;
} else {
field[i / 4] = 0;
}
}
return field;
}
Insert cell
particles = {
text;
reset;
const particles = {
x: new Uint16Array(count),
y: new Uint16Array(count),
stuck: new Uint8Array(count)
};
for (let i = 0; i < count; i++) {
resetSingleParticle(particles, i);
}
return particles;
}
Insert cell
resetSingleParticle = (particles, i) => {
let x = Math.floor(Math.random() * width);
let y = Math.floor(Math.random() * height);

while (field[y * width + x]) {
x = Math.floor(Math.random() * width);
y = Math.floor(Math.random() * height);
}

particles.x[i] = x;
particles.y[i] = y;
}
Insert cell
function alone(i) {
let cx = particles.x[i];
let cy = particles.y[i];

let lx = cx - 1;
let rx = cx + 1;
let ty = cy - 1;
let by = cy + 1;

if (
cx <= 0 ||
cx > width ||
lx <= 0 ||
lx > width ||
rx <= 0 ||
rx > width ||
cy <= 0 ||
cy > height ||
ty <= 0 ||
ty > height ||
by <= 0 ||
by > height
) {
return true;
}

cy *= width;
by *= width;
ty *= width;

if (field[cx + ty] || field[lx + cy] || field[rx + cy] || field[cx + by]) {
return false;
}

if (field[lx + ty] || field[lx + by] || field[rx + ty] || field[rx + by]) {
return false;
}

return true;
}
Insert cell
updateSingleParticle = i => {
let x = particles.x[i];
let y = particles.y[i];

x += Math.random() > 0.5 ? 1 : -1;
y += Math.random() > 0.5 ? 1 : -1;

if (x < 0 || y < 0 || x > width || y >= height) {
return resetSingleParticle(particles, i);
}

particles.x[i] = x;
particles.y[i] = y;

if (!alone(i)) {
particles.stuck[i] = mutable generation;
mutable generation = mutable generation + 1;
field[y * width + x] = 1;
}
}
Insert cell
Insert cell
count = 40000
Insert cell
height = width * 0.75
Insert cell
Insert cell
Insert cell
Insert cell
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