xxxxxxxxxx
78
let seeds = [];
function setup() {
createCanvas(600, 400);
// generate random points
for (let i = 0; i < 100; i++) {
seeds.push([random(width), random(height)]);
}
stroke(255);
strokeWeight(1);
frameRate(2);
noFill();
}
function draw() {
background(0);
const delaunay = d3.Delaunay.from(seeds);
const voronoi = delaunay.voronoi([0, 0, width, height]);
const polygons = Array.from(voronoi.cellPolygons());
const areas = calculateAreas(polygons);
// render voronoi polygons
renderPolygons(polygons, areas);
}
function calculateAreas(polygons) {
const areas = [];
for (let polygon of polygons) {
let area = 0;
for (let i = 0; i < polygon.length; i++) {
const j = (i + 1) % polygon.length;
area += polygon[i][0] * polygon[j][1];
area -= polygon[j][0] * polygon[i][1];
}
areas.push(Math.abs(area / 2));
}
return areas;
}
function renderPolygons(polygons, areas) {
const minArea = min(areas);
const maxArea = max(areas);
for (let polygon of polygons) {
// fill color based on the area
const area = areas[polygons.indexOf(polygon)];
// fill blue scale color
const color = map(area, minArea, maxArea, 0, 200);
fill(color);
// draw the polygon
beginShape();
for (let point of polygon) {
vertex(point[0], point[1]);
}
endShape();
}
}
function renderDelaunay(delaunay) {
const { points, triangles } = delaunay;
for (let i = 0; i < triangles.length; i += 3) {
// get the points index of the triangle
const a = 2 * triangles[i + 0];
const b = 2 * triangles[i + 1];
const c = 2 * triangles[i + 2];
// draw the triangle
triangle(points[a], points[a + 1], points[b], points[b + 1], points[c], points[c + 1]);
}
}