<!DOCTYPE html>
<html>
<head>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="voronoiCanvas" width="600" height="400"></canvas>
<script>
// Get the canvas element
var canvas = document.getElementById("voronoiCanvas");
var ctx = canvas.getContext("2d");
// Generate random points as seeds
var numPoints = 50;
var points = [];
for (var i = 0; i < numPoints; i++) {
points.push({
x: Math.random() * canvas.width,
y: Math.random() * canvas.height,
});
}
// Calculate distance between two points
function distance(p1, p2) {
var dx = p1.x - p2.x;
var dy = p1.y - p2.y;
return Math.sqrt(dx * dx + dy * dy);
}
// Find the closest seed point to a given point
function findClosestSeedPoint(point) {
var minDistance = Number.MAX_VALUE;
var closestPointIndex = -1;
for (var i = 0; i < numPoints; i++) {
var d = distance(point, points[i]);
if (d < minDistance) {
minDistance = d;
closestPointIndex = i;
}
}
return closestPointIndex;
}
// Assign colors based on proximity
function assignColors() {
var imageData = ctx.createImageData(canvas.width, canvas.height);
var data = imageData.data;
for (var y = 0; y < canvas.height; y++) {
for (var x = 0; x < canvas.width; x++) {
var closestPointIndex = findClosestSeedPoint({ x: x, y: y });
// Set color based on the index of the closest point
var colorIndex = closestPointIndex % 16;
var baseColor = colorIndex * 16;
var pixelIndex = (y * canvas.width + x) * 4;
data[pixelIndex] = baseColor; // Red channel
data[pixelIndex + 1] = baseColor; // Green channel
data[pixelIndex + 2] = baseColor; // Blue channel
data[pixelIndex + 3] = 255; // Alpha channel
}
}
ctx.putImageData(imageData, 0, 0);
}
// Draw the Voronoi diagram
function drawVoronoi() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
assignColors();
// Draw seed points
ctx.fillStyle = "red";
for (var i = 0; i < numPoints; i++) {
ctx.beginPath();
ctx.arc(points[i].x, points[i].y, 3, 0, 2 * Math.PI);
ctx.fill();
}
}
// Redraw the diagram when the window is resized
window.addEventListener("resize", function () {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
drawVoronoi();
});
// Initial drawing
drawVoronoi();
</script>
</body>
</html>