Write the core of a voronoi stained glass generator in plain JavaScript, no libraries. One function, voronoi(seeds, mask, w, h, label, edge), that for every pixel inside a mask finds the nearest and second nearest seed, writes the nearest index into label, and writes the exact distance to the shared cell edge into edge using (d2^2 - d1^2) / (2 * |s1 - s2|) so lead lines come out the same width everywhere. A second function, lloyd(seeds, label, w, h, rate), that moves every seed toward the centroid of its cell by rate and returns the average distance moved. Then render a quick check: 80 random seeds in a gothic arch mask, raw on the left and after 8 lloyd passes on the right, seeds as red dots.
the second nearest seed is the trick. it gives you exact distance to the edge for free, so you can draw lead as a threshold on that number instead of tracing polygons. lloyd evens out the cells so it reads like cut glass, not random shards.
// nearest + second-nearest seed per pixel, and exact distance to the shared edge
function voronoi(seeds, mask, w, h, label, edge) {
for (let y = 0, i = 0; y < h; y++) for (let x = 0; x < w; x++, i++) {
if (!mask[i]) { label[i] = -1; continue; }
let a = 0, b = 0, da = 1e12, db = 1e12;
for (let k = 0; k < seeds.length; k++) {
const dx = x - seeds[k].x, dy = y - seeds[k].y, d = dx * dx + dy * dy;
if (d < da) { db = da; b = a; da = d; a = k; }
else if (d < db) { db = d; b = k; }
}
label[i] = a;
const sx = seeds[a].x - seeds[b].x, sy = seeds[a].y - seeds[b].y;
edge[i] = (db - da) / (2 * Math.hypot(sx, sy)); // px to the bisector line
}
}
// one lloyd pass: pull every seed toward the centroid of its own cell
function lloyd(seeds, label, w, h, rate = 1) {
const n = seeds.length, sx = new Float64Array(n), sy = new Float64Array(n), c = new Uint32Array(n);
for (let y = 0, i = 0; y < h; y++) for (let x = 0; x < w; x++, i++) {
const l = label[i];
if (l < 0) continue;
sx[l] += x; sy[l] += y; c[l]++;
}
let moved = 0;
for (let k = 0; k < n; k++) {
if (!c[k]) continue;
const dx = (sx[k] / c[k] - seeds[k].x) * rate, dy = (sy[k] / c[k] - seeds[k].y) * rate;
seeds[k].x += dx; seeds[k].y += dy; moved += Math.hypot(dx, dy);
}
return moved / n; // average px moved, use it to stop early
}








