Unlisted
Edited
Jun 27, 2024
2 stars
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
width = 500
Insert cell
height = 500
Insert cell
Insert cell
Insert cell
Insert cell
function voronoigrid(
mystep = 50,
width = 1000,
height = 1000,
colors = ["red", "green", "blue", "yellow"]
) {
let grid = [];
let nb = Math.round((width / mystep) * (height / mystep));
for (let i = 0; i < nb; i++) {
grid.push([Math.random() * width, Math.random() * height]);
}

let voronoi = d3.Delaunay.from(
grid,
(d) => d[0],
(d) => d[1]
).voronoi([0, 0, width, height]);

// build object
let result = grid.map((d, i) => {
return {
type: "Feature",
geometry: {
type: "Polygon",
coordinates: [voronoi.cellPolygon(i)]
},
properties: {
index: i,
col: "",
x: grid[i][0],
y: grid[i][1]
}
};
});

const topo = topojson.neighbors(
topojson.topology({
result: { type: "FeatureCollection", features: result }
}).objects.result.geometries
);

const nbvoisins = new Map(topo.map((d, i) => [i, d.length]));

result = result.map((d) => ({
type: "Feature",
properties: {
...d.properties,
voisins: topo[d.properties.index],
nb: nbvoisins.get(d.properties.index)
},
geometry: d.geometry
}));

result = result.sort((a, b) =>
d3.descending(a.properties.nb, b.properties.nb)
);

let id = 0;
console.log(id);

while (result.find((d) => d.properties.col == "") != undefined) {
console.log("");

let curentpoly = result.find((d) => d.properties.index == id);

//return curentpoly;

let neighcol = result
.filter((d) => curentpoly.properties.voisins.includes(d.properties.index))
.map((d) => d.properties.col);

const newcol = colors.filter((x) => !neighcol.includes(x))[0];

curentpoly.properties.col = newcol;

let nextid =
result
.filter((d) =>
curentpoly.properties.voisins.includes(d.properties.index)
)
.find((d) => d.properties.col == "")?.properties.index ||
result.find((d) => d.properties.col == "")?.properties.index;
id = nextid;
console.log(id);
}
return result;
}
Insert cell
Insert cell
topojson = require("topojson-client@3", "topojson-server@3")
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