Public
Edited
Oct 24, 2022
1 star
Insert cell
Insert cell
canvas = {
const context = DOM.context2d(width, height);

function update() {
const delaunay = d3.Delaunay.from(particles);
const voronoi = delaunay.voronoi([0.5, 0.5, width - 0.5, height - 0.5]);
context.clearRect(0, 0, width, height);

context.beginPath();
voronoi.render(context);
voronoi.renderBounds(context);
context.fillStyle = "#383326";
for (const i of particles) voronoi.renderCell(i, context);
context.fill();
context.strokeStyle = "#222";
context.stroke();

// https://coolors.co/ffd555-ffb833-ff9428-ff4e26
context.fillStyle = "#ff9626";
context.beginPath();
voronoi.renderCell(0, context);
context.fill();
context.strokeStyle = "#222";
context.stroke();

const Y = true_neighbors(voronoi, 0),
U = [...delaunay.neighbors(0)].filter((j) => !Y.includes(j));

//yellow
context.fillStyle = "#FFCC33";
context.beginPath();
for (const j of U) voronoi.renderCell(j, context);
context.fill();
context.strokeStyle = "#222";
context.stroke();

//orange
context.fillStyle = "#FFB429";
context.beginPath();
for (const j of Y) voronoi.renderCell(j, context);
context.fill();
context.strokeStyle = "#222";
context.stroke();

context.beginPath();
delaunay.render(context);
context.strokeStyle = "#A21D1D55";
context.stroke();

context.beginPath();
context.fillStyle = "#A21D1D55";
delaunay.renderPoints(context);
context.fill();
}

context.canvas.ontouchmove = context.canvas.onmousemove = (event) => {
event.preventDefault();
particles[0] = [event.layerX, event.layerY];
update();
};

context.canvas.onclick = (event) => {
event.preventDefault();
// particles[0] = [event.layerX, event.layerY];
particles.push([event.layerX, event.layerY]);
update();
};

update();

return context.canvas;
}
Insert cell
particles = Array.from({ length: n }, () => [
Math.random() * width,
Math.random() * height
])
Insert cell
height = 800
Insert cell
n = 100
Insert cell
function true_neighbors(voronoi, i) {
const n = [];
const ai = new Set((voronoi.cellPolygon(i) || []).map(String));
for (const j of voronoi.delaunay.neighbors(i))
for (const c of voronoi.cellPolygon(j) || [])
if (ai.has(String(c))) n.push(j);
return n;
}
Insert cell
d3 = require("d3-delaunay@5")
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