0 Spicy Yoghurt | Last updated: 26 November 2026 | Algorithm tutorial
Voronoi diagrams and Delaunay triangulation in JavaScript
A Voronoi diagram splits a canvas or a map into cells around a set of points, so every spot belongs to the point closest to it. Build one step by step in JavaScript, and use it for game maps, mosaics and stipple art.
Every colored shape in the demo below is a cell, and each cell belongs to one of the white dots. Any spot inside a cell is closer to its own dot than to any other dot. Drag a dot, or click or tap to add one, and watch the cells around it change shape:
By the end of this tutorial, you'll know how to build this yourself. Along the way, you'll connect the dots with triangles, spread them out evenly, turn a photo into stipple art and stained glass, and build a game map.
What is a Voronoi diagram?
A Voronoi diagram starts with a set of points, also called sites or seeds. Around each point, it draws a cell: the area of all the spots that are closer to that point than to any other point. Together, the cells cover the whole plane, without gaps or overlaps.
Move your mouse over the demo below, or touch it with your finger. The solid line goes from the red dot under your mouse or finger to the closest point, and the cell of that point lights up. The dashed line goes to the next-closest point:
Now move toward the border between two cells, and keep an eye on the two distances in the corner of the demo. Right on the border, they're the same. That's what the edges of a Voronoi diagram are: lines of spots that are the same distance from two points. A corner where three cells meet is the same distance from all three points.
You've probably seen Voronoi diagrams before, even if you didn't know the name. If every child goes to the closest school, the school districts form a Voronoi diagram. Nature makes them too: you can see the pattern on the skin of a giraffe, in the wings of a dragonfly and in dry, cracked mud.
One famous example comes from London. In 1854, the physician John Snow mapped the deaths from a cholera outbreak. A later version of his map shows a line around the homes that were closest to the Broad Street pump by walking distance. Most of the deaths were inside that line, which pointed to the pump as the source.
Color every pixel by its closest point
The most direct way to draw a Voronoi diagram is to follow the definition. Go through every pixel of the canvas, find the point that's closest to it, and give the pixel the color of that point.
The code in this tutorial draws on an HTML5 canvas. canvas is the <canvas> element on your page, and context is its 2D drawing context. The tutorial on setting up an HTML5 canvas shows how to get both.
First, you need some points. createPoints() makes an array of random points, each with a color from the colors array. A color is an array of three numbers from 0 to 255: red, green and blue. With more points than colors, i % colors.length starts again at the first color after the last one:
const colors = [
[255, 192, 192],
[255, 216, 192],
[255, 231, 168],
[155, 228, 184],
[128, 204, 216],
[224, 192, 255],
[224, 202, 192]
];
function createPoints(count) {
let points = [];
for (let i = 0; i < count; i++) {
points.push({
x: Math.random() * canvas.width,
y: Math.random() * canvas.height,
color: colors[i % colors.length]
});
}
return points;
}The next function finds the closest point to a spot on the canvas. It goes through all the points and keeps the one with the smallest distance so far:
function getClosestPoint(x, y, points) {
let closest = points[0];
let closestDistance = Infinity;
for (let point of points) {
let dx = point.x - x;
let dy = point.y - y;
let distance = dx * dx + dy * dy;
if (distance < closestDistance) {
closestDistance = distance;
closest = point;
}
}
return closest;
}You might expect a square root here. The real distance is the square root of dx * dx + dy * dy, but you only need to know which point is closest. If one distance is smaller than another, its square is smaller too, so you can skip Math.sqrt() and save some time.
To set the color of individual pixels, use an ImageData object. It holds four numbers for every pixel: red, green, blue and alpha, each from 0 to 255. Alpha is how solid the pixel is, and 255 means fully solid. createImageData() gives you an empty one the size of the canvas, and putImageData() draws it:
function drawVoronoi(points) {
let image = context.createImageData(canvas.width, canvas.height);
for (let y = 0; y < canvas.height; y++) {
for (let x = 0; x < canvas.width; x++) {
let color = getClosestPoint(x, y, points).color;
let index = (y * canvas.width + x) * 4;
image.data[index] = color[0];
image.data[index + 1] = color[1];
image.data[index + 2] = color[2];
image.data[index + 3] = 255;
}
}
context.putImageData(image, 0, 0);
}
let points = createPoints(50);
drawVoronoi(points);image.data is one long array with the pixels row by row, four numbers per pixel. So the pixel in column x of row y starts at index (y * canvas.width + x) * 4. A color from createPoints() is already an array of three numbers, so drawVoronoi() can copy them into image.data one by one.
Here's the result, with the points drawn on top as black dots. Pick a number of points, and the canvas shows how long it took to draw:
This works, but it's slow. The canvas is 750 by 400 pixels, so that's 300,000 pixels. With 50 points, you calculate 15 million distances, and with 200 points, 60 million. That's fine for a picture you draw once. But at 60 frames per second, a frame gets only about 16 milliseconds for everything in your game. That's not enough time to redraw all the pixels while you drag a point around. You'll find a faster way further down this page.
Change how you measure distance
So far, the distance between two points has been the length of a straight line between them. That's called the Euclidean distance. But you can measure distance in other ways, and each one gives the cells a different shape. Here are two that are popular in games:
- Manhattan distance - Add up the horizontal and the vertical distance, as if you were walking along the streets of a city laid out in a grid. The tutorial on pathfinding algorithms uses it on a grid where you can only move up, down, left or right.
- Chebyshev distance - Take the larger of the horizontal and the vertical distance. That's the number of moves a king needs to get somewhere on a chessboard.
Give getClosestPoint() an extra parameter, type, and calculate the distance with getDistance(dx, dy, type):
function getDistance(dx, dy, type) {
if (type == 'manhattan') {
return Math.abs(dx) + Math.abs(dy);
}
if (type == 'chebyshev') {
return Math.max(Math.abs(dx), Math.abs(dy));
}
return Math.sqrt(dx * dx + dy * dy);
}type is 'manhattan', 'chebyshev' or anything else for the straight-line distance. This time, the square root is back, because in a moment, you'll need the real distance. Here's getClosestPoint() with the change:
function getClosestPoint(x, y, points, type) {
let closest = points[0];
let closestDistance = Infinity;
for (let point of points) {
let distance = getDistance(point.x - x, point.y - y, type);
if (distance < closestDistance) {
closestDistance = distance;
closest = point;
}
}
return closest;
}You can also use the distance itself as a color. Color each pixel by how far away its closest point is: dark near a point and light far away. That's a distance map, and it looks like a pattern of soft blobs. Or keep track of the distance to the second-closest point too, and color each pixel by the difference between the two distances. That difference is zero right on an edge, so only the edges come out dark:
let first = Infinity;
let second = Infinity;
for (let point of points) {
let distance = getDistance(point.x - x, point.y - y, type);
if (distance < first) {
second = first;
first = distance;
} else if (distance < second) {
second = distance;
}
}
let shade = Math.min((second - first) * 25, 255);In drawVoronoi(), replace the call to getClosestPoint() with this loop, and give drawVoronoi() a type parameter, which it passes on to getDistance(). When the loop finds a new closest point, the old closest point becomes the second closest. Use shade for the red, green and blue of the pixel, and you get dark edges on a white background. The 25 sets how thin the lines are: the bigger the number, the faster the shade turns white as you move away from an edge. For the distance map, use Math.min(first * 2, 255) as the shade instead.
Try all of it in the demo below. Pick an option under Distance, and switch Show to Distance map or Edges:
With Manhattan and Chebyshev distance, the edges only run straight across, straight up and down, or at 45 degrees. That gives your cells a blocky look, which fits a game on a grid.
With Edges, you can even get a dark patch instead of a line. That happens, for example, with Manhattan distance when the line between two points runs at almost exactly 45 degrees. Then a whole area is almost the same distance from both points.
Patterns like the distance map and the edges are known as Worley noise, or cellular noise. Games and 3D programs use them as textures for stone, scales, water and skin, often with thousands of points.
Draw each cell as a polygon
A picture made of pixels is nice to look at, but you can't do much else with it. For example, you can't draw a line around a cell or work out how big it is. For that, you need each cell as a polygon: a list of corners. And there's a neat way to get one.
Take two points, a and b. The perpendicular bisector is the line of all the spots that are exactly as far from a as from b. It crosses the line between a and b right in the middle, at a right angle. Everything on a's side of the bisector is closer to a, and everything on b's side is closer to b.
So here's how you build the cell of point a. Start with a rectangle the size of the canvas. Then, for every other point b, cut the shape along the bisector between a and b, and throw away the part on b's side. What's left after the last cut is the cell of a. Click or tap a point in the demo below to watch its cell being cut out:
The red dot is the point whose cell you're building, and the blue dot is the other point for this cut. The blue line is the bisector between them, and the blue area is the part that's about to go. Some cuts don't change anything, because the bisector misses what's left of the cell.
To cut a polygon along a line, go around its corners and check which side of the line each corner is on. Keep the corners on the side of a. Where an edge of the polygon crosses the line, add the crossing point too:
function clipPolygon(polygon, a, b) {
let middleX = (a.x + b.x) / 2;
let middleY = (a.y + b.y) / 2;
let result = [];
for (let i = 0; i < polygon.length; i++) {
let p = polygon[i];
let q = polygon[(i + 1) % polygon.length];
// Below 0 is the side of a, above 0 the side of b
let sideP =
(p.x - middleX) * (b.x - a.x) +
(p.y - middleY) * (b.y - a.y);
let sideQ =
(q.x - middleX) * (b.x - a.x) +
(q.y - middleY) * (b.y - a.y);
if (sideP <= 0) {
result.push(p);
}
if ((sideP <= 0) != (sideQ <= 0)) {
let t = sideP / (sideP - sideQ);
result.push({
x: p.x + (q.x - p.x) * t,
y: p.y + (q.y - p.y) * t
});
}
}
return result;
}The loop looks at each edge of the polygon, from corner p to the next corner, q. After the last corner, (i + 1) % polygon.length wraps around to the first one. sideP tells you which side of the bisector p is on. It multiplies the offset from the midpoint to p by the offset from a to b: x times x, plus y times y. This is called a dot product. The result is 0 when the two offsets are at a right angle, which happens when p lies exactly on the bisector. It's above 0 when p is on b's side, and below 0 when it's on a's side.
If p and q are on different sides, t tells you where the edge crosses the bisector: 0 at p and 1 at q. Along the edge, the side value changes steadily from sideP to sideQ. t is the fraction of the way from p to q where that value is 0.
Now getCell() starts with the rectangle and cuts it once for every other point:
function getCell(point, points) {
let cell = [
{x: 0, y: 0},
{x: canvas.width, y: 0},
{x: canvas.width, y: canvas.height},
{x: 0, y: canvas.height}
];
for (let other of points) {
if (other != point) {
cell = clipPolygon(cell, point, other);
}
}
return cell;
}Because every cell starts as the canvas, it also ends at the edges of the canvas. In a real Voronoi diagram, the cells on the outside go on forever, so stopping at the canvas is a handy extra.
To draw a cell, trace its corners with a path, the same way you'd draw a triangle. The tutorial on drawing lines and shapes on the canvas explains paths, fill() and stroke(). A color for fillStyle is a string like 'rgb(255, 192, 192)', so join() turns the three numbers of a color into one string:
function drawCell(cell, color) {
context.beginPath();
context.moveTo(cell[0].x, cell[0].y);
for (let i = 1; i < cell.length; i++) {
context.lineTo(cell[i].x, cell[i].y);
}
context.closePath();
context.fillStyle = 'rgb(' + color.join(', ') + ')';
context.fill();
context.stroke();
}
for (let point of points) {
drawCell(getCell(point, points), point.color);
}How fast is it? With 200 points, each cell gets cut 199 times, which sounds like a lot. But a cut only looks at the handful of corners the cell has left, so on a laptop, 200 cells take about 4 milliseconds. That's fast enough to redraw every frame while you drag a point, like in the demo at the top of this page.
For thousands of points, you only need the bisectors between a point and the points near it, because a point far away can't cut anything off. The tutorial on flocking with boids uses a grid to find nearby boids quickly, and the same trick works here.
Connect neighboring points with a Delaunay triangulation
Two points are neighbors if their cells share an edge. Draw a line between every pair of neighbors, and the lines split the space between the points into triangles. That's the Delaunay triangulation, named after the mathematician Boris Delaunay, who described it in 1934.
There are lots of ways to connect a set of points with triangles. The circle through the three corners of a triangle is its circumcircle. What makes the Delaunay triangulation special is one rule: no circumcircle has another point inside it. Move your mouse or finger over a triangle in the demo below to see its circumcircle. You can drag the points too:
However you move the points, the red circle stays empty. A long, thin triangle has a circumcircle that's huge compared to the triangle itself, and that circle almost always has another point inside it. So the Delaunay triangulation avoids long, thin triangles wherever it can. That's why it's used for meshes of 3D models and terrain, and for the low-poly art you'll make later on this page.
Here's how to find the circumcircle of three points a, b and c. The formula comes from the fact that the center is the same distance from all three corners:
function getCircumcircle(a, b, c) {
let d = 2 * (a.x * (b.y - c.y) + b.x * (c.y - a.y) +
c.x * (a.y - b.y));
let aa = a.x * a.x + a.y * a.y;
let bb = b.x * b.x + b.y * b.y;
let cc = c.x * c.x + c.y * c.y;
let x = (aa * (b.y - c.y) + bb * (c.y - a.y) +
cc * (a.y - b.y)) / d;
let y = (aa * (c.x - b.x) + bb * (a.x - c.x) +
cc * (b.x - a.x)) / d;
let dx = a.x - x;
let dy = a.y - y;
return {x: x, y: y, radiusSquared: dx * dx + dy * dy};
}
function isInCircle(point, circle) {
let dx = point.x - circle.x;
let dy = point.y - circle.y;
return dx * dx + dy * dy < circle.radiusSquared;
}The circle stores the squared radius, so isInCircle() can compare squared distances again, without a square root.
If the three points lie on a straight line, d is 0, and there's no circle. Dividing by d then gives Infinity or NaN. The triangulation in the next section never builds a flat triangle like that, not even with points on a grid. So this only matters if you call getCircumcircle() yourself.
Build the triangulation with the Bowyer–Watson algorithm
The Bowyer–Watson algorithm builds a Delaunay triangulation by adding the points one at a time. It starts with one big triangle around all the points, and makes sure that after every new point, no circumcircle has a point inside it. Adrian Bowyer and David Watson both came up with it in 1981, independently of each other. For each new point, the algorithm takes three steps:
- Find the bad triangles - Look for every triangle whose circumcircle contains the new point. Those triangles break the rule.
- Remove them - Together, the bad triangles leave a hole around the new point.
- Fill the hole - Connect every edge along the border of the hole to the new point.
When all the points are in, remove every triangle that shares a corner with the big triangle. Those corners aren't real points. Watch it in the demo below:
The red dot is the new point, and the gray dots are the corners of the big triangle. The red triangles have the new point inside their dashed circumcircles. The thick red line is the border of the hole they leave behind, and the green triangles are the new ones.
In code, a triangle is an object with its three corners and its circumcircle. triangulate() follows the three steps for every point:
function createTriangle(a, b, c) {
return {
corners: [a, b, c],
circle: getCircumcircle(a, b, c)
};
}
function triangulate(points) {
// A triangle that's much bigger than the canvas, with its
// corners 100 million pixels away
let big = [
{x: -100000000, y: -100000000},
{x: 100000000, y: -100000000},
{x: 0, y: 100000000}
];
let triangles = [createTriangle(big[0], big[1], big[2])];
for (let point of points) {
let badTriangles = triangles.filter(function (triangle) {
return isInCircle(point, triangle.circle);
});
let hole = getHoleEdges(badTriangles);
triangles = triangles.filter(function (triangle) {
return !badTriangles.includes(triangle);
});
for (let edge of hole) {
triangles.push(
createTriangle(edge[0], edge[1], point)
);
}
}
return triangles.filter(function (triangle) {
return !triangle.corners.some(function (corner) {
return big.includes(corner);
});
});
}To find the border of the hole, getHoleEdges() collects the three edges of every bad triangle. An edge that two bad triangles share is inside the hole, so it's dropped. An edge that belongs to only one bad triangle is part of the border of the hole:
function getHoleEdges(badTriangles) {
let edges = [];
for (let triangle of badTriangles) {
let [a, b, c] = triangle.corners;
edges.push([a, b], [b, c], [c, a]);
}
return edges.filter(function (edge) {
let count = edges.filter(function (other) {
return (other[0] == edge[0] && other[1] == edge[1]) ||
(other[0] == edge[1] && other[1] == edge[0]);
}).length;
return count == 1;
});
}Make the big triangle much bigger than the area your points cover. If a corner of the big triangle is too close to the points, it can end up inside a circumcircle that should be empty. When that happens, you lose triangles along the outer edge. That's more likely than you'd expect, because a long, thin triangle along the edge can have a huge circumcircle. With the corners 10,000 pixels away, about one in three sets of 50 random points lost a triangle in our tests. With the corners 100 million pixels away, as in triangulate(), none did.
The big triangle in the demo has to fit on the canvas, so the demo only uses sets of points that don't lose any triangles.
On a laptop, this version takes about 14 milliseconds for 1,000 points, and about 150 milliseconds for 3,000. Three times as many points take about 10 times as long, because every new point checks all the triangles built so far. Faster versions only look at the triangles around the new point.
See how Voronoi and Delaunay fit together
The Voronoi diagram and the Delaunay triangulation are two views of the same thing. Mathematicians say they're dual to each other. The demo below shows both. Drag a point around, and turn on Circumcircles:
Here's what the demo shows:
- The lines are at right angles - Each blue line between two neighbors is at a right angle to the dark edge between their cells. That edge lies on the bisector between the two points.
- The corners are the centers - The red dots are the centers of the circumcircles, and each one sits on a corner of a cell. A corner is the same distance from three points, and so is the center of the circle through them.
- The circles are empty - With Circumcircles on, you can see that no circle contains a point, wherever you drag the points.
So once you have the triangles, you get the cells almost for free. To build the cell of a point, take every triangle that has that point as a corner, and collect the centers of their circumcircles. Then sort the centers by their angle around the point, so they go around in order. Math.atan2() gives the angle of the direction from the point to a center:
function getCellFromTriangles(point, triangles) {
let corners = [];
for (let triangle of triangles) {
if (triangle.corners.includes(point)) {
corners.push(triangle.circle);
}
}
corners.sort(function (p, q) {
return Math.atan2(p.y - point.y, p.x - point.x) -
Math.atan2(q.y - point.y, q.x - point.x);
});
return corners;
}That's how the JavaScript library d3-delaunay builds its Voronoi diagrams so quickly: it starts from a triangulation made by Delaunator, a fast triangulation library. The triangles also give you the neighbors of every point: the other corners of its triangles.
There are two catches for the outer points, though:
- Open cells - A point on the outer edge of the triangulation doesn't have triangles all the way around it, so its cell isn't closed. You have to close it off at the edge of the canvas yourself, like getCell() does.
- Corners outside the canvas - When one angle of a triangle is larger than 90 degrees, the center of its circumcircle lies outside the triangle, and sometimes even outside the canvas. You have to cut off that corner of the cell too.
So for a few hundred points, getCell() is the simpler choice.
Spread the points evenly with Lloyd's algorithm
Random points clump together. Some cells end up tiny and others huge: with 100 random points, the biggest cell is often 20 times as big as the smallest. For a game map or a mosaic, you usually want something more even.
Lloyd's algorithm, also called Lloyd relaxation, fixes that. Move every point to the center of its cell, build the cells again, and repeat. With every step, the big cells shrink and the small ones grow. Press Step a few times, or Play:
The first steps make the biggest difference. With 100 points, the biggest cell is about 4 times as big as the smallest after 3 steps, and less than twice as big after 30. The cells slowly turn into hexagons, like the cells of a honeycomb.
The center of a cell here is its centroid: the spot where a cardboard cutout of the cell would balance on the tip of a pencil. getCentroid() works it out from the corners with a standard formula, based on the shoelace formula for the area of a polygon. relax() uses getCentroid() to take one step:
function getCentroid(polygon) {
let area = 0;
let x = 0;
let y = 0;
for (let i = 0; i < polygon.length; i++) {
let p = polygon[i];
let q = polygon[(i + 1) % polygon.length];
let cross = p.x * q.y - q.x * p.y;
area += cross;
x += (p.x + q.x) * cross;
y += (p.y + q.y) * cross;
}
area /= 2;
return {x: x / (6 * area), y: y / (6 * area)};
}
function relax(points) {
let centers = points.map(function (point) {
return getCentroid(getCell(point, points));
});
points.forEach(function (point, i) {
point.x = centers[i].x;
point.y = centers[i].y;
});
}relax() first works out all the new positions, and only then moves the points. If it moved each point right away, the cells of the next points would already be different.
Turn a photo into stipple art
Lloyd's algorithm can do more than spread points evenly. Give every pixel of a photo a weight: the darker the pixel, the heavier it is. Then move each point to the weighted center of its cell. That pulls the point toward the dark parts. Draw only the points, as small dots, and you get a drawing made of dots: stipple art. This trick is called weighted Voronoi stippling, and it comes from a 2002 paper by Adrian Secord. Pick a photo, and watch the dots find their place:
After a few dozen steps, the dots settle: close together where the photo is dark, and far apart where it's light. That's when the shapes from the photo come into focus.
The demo starts with 3,000 dots that are already packed more closely where the photo is dark. To place them, it picks random spots and keeps each one only if another random number is smaller than the weight of the pixel there. This head start matters, because a dot only moves within its own cell. If you start with plain random points from createPoints() instead, far too many dots stay in the light parts of the photo.
To find the weighted center of every cell, go through all the pixels, like drawVoronoi() does. For each pixel, find the closest point, and add the position of the pixel, times its weight, to the totals of that point:
function stipple(points, image) {
for (let point of points) {
point.totalWeight = 0;
point.totalX = 0;
point.totalY = 0;
}
for (let y = 0; y < image.height; y++) {
for (let x = 0; x < image.width; x++) {
let index = (y * image.width + x) * 4;
let brightness = (image.data[index] +
image.data[index + 1] +
image.data[index + 2]) / 765;
let darkness = 1 - brightness;
let weight = darkness * darkness;
let closest = getClosestPoint(x, y, points);
closest.totalWeight += weight;
closest.totalX += x * weight;
closest.totalY += y * weight;
}
}
for (let point of points) {
if (point.totalWeight > 0) {
point.x = point.totalX / point.totalWeight;
point.y = point.totalY / point.totalWeight;
}
}
}image is an ImageData object with the pixels of the photo. To get one, draw the photo on a canvas with drawImage(), and call getImageData() on its context. The tutorial on images and sprite animations shows how to load and draw a photo.
765 is 3 times 255, so brightness goes from 0 for black to 1 for white. Squaring darkness makes dark pixels count even more than light ones, so the dots gather more clearly in the dark parts of the photo.
With 3,000 points and 300,000 pixels, the loop in getClosestPoint() would take too long for an animation. So the demo only looks at every other pixel in each direction. It also puts the points in the squares of a grid, so for each pixel, it only checks the points in the squares nearby. The tutorial on flocking uses the same kind of grid.
Make stained glass and low-poly art
You can also use the colors of a photo. For stained glass, fill each Voronoi cell with the average color of the pixels inside it, and draw thick dark lines between the cells, like the lead in a church window. For low-poly art, fill each Delaunay triangle with the color of the photo at the triangle's center: the average position of its three corners. Try both, with your own photo if you like. Your photo stays in your browser, and nothing gets uploaded:
For the stained glass, the demo first takes two steps of Lloyd's algorithm, so the pieces of glass are more even in size. To get the average color of a cell, it goes through the pixels the same way stipple() does. For every pixel, it adds the red, green and blue to the running totals for the closest point.
Low-poly art looks best with more points where the photo has a lot of detail, such as the edges of the peppers in the demo, and fewer in the flat areas. The demo measures how much the brightness changes from one pixel to the next, and puts more points where it changes a lot. Plain random points work too, but the edges of the peppers come out less sharp. Triangles only reach as far as the outermost points, so the demo also puts points along the edges of the canvas. Coloring the triangles takes only a few lines:
function drawLowPoly(points, image) {
for (let triangle of triangulate(points)) {
let [a, b, c] = triangle.corners;
let x = Math.floor((a.x + b.x + c.x) / 3);
let y = Math.floor((a.y + b.y + c.y) / 3);
let index = (y * image.width + x) * 4;
let red = image.data[index];
let green = image.data[index + 1];
let blue = image.data[index + 2];
context.beginPath();
context.moveTo(a.x, a.y);
context.lineTo(b.x, b.y);
context.lineTo(c.x, c.y);
context.closePath();
context.fillStyle =
'rgb(' + red + ', ' + green + ', ' + blue + ')';
context.strokeStyle = context.fillStyle;
context.fill();
context.stroke();
}
}The stroke in the same color covers the thin seams the browser can leave between two triangles that touch.
Use a Voronoi diagram in your game
Voronoi diagrams come in handy in games all the time. Here are three ways to use one:
- Find the closest thing - Which enemy is closest to the player? Which tower covers this tile? Those are Voronoi questions, and getClosestPoint() answers them for one spot.
- Split a map into regions - Spread the points out evenly with Lloyd's algorithm, and give each cell a type, like water, beach, grass, forest or mountain. The Delaunay triangulation tells you which regions are neighbors, for borders, roads and rivers.
- Break things - Put points around the spot where something gets hit, and turn every cell into a piece. With more points close to the impact, the pieces there are small, and farther away they're big.
The demo below has two examples. With Map, click or tap the island to make a new one. With Broken glass, click or tap the window to break it, and press Fix the window to try again:
For the island, every cell gets a height. Cells in the middle of the canvas are high, and cells near the edges are low enough to end up under water. The demo also adds a few random hills, so every island has its own shape. Then the height picks the color of the cell:
function getHeight(point) {
let dx = (point.x - canvas.width / 2) / (canvas.width / 2);
let dy = (point.y - canvas.height / 2) / (canvas.height / 2);
return 0.75 - Math.sqrt(dx * dx + dy * dy);
}
function getRegionColor(height) {
if (height < 0) {
// Water
return '#80ccd8';
}
if (height < 0.06) {
// Beach
return '#ffe7a8';
}
if (height < 0.3) {
// Grass
return '#9be4b8';
}
// Forest
return '#37c871';
}dx and dy go from -1 at one edge of the canvas to 1 at the other edge. In the middle, they're both 0, so the height is 0.75. Outside an oval around the middle that reaches three quarters of the way to each edge, it drops below 0, and the cell is under water. The demo has a few more colors, for deep water, mountains and snow.
Want the same island every time, so players can share a map with a single number? The tutorial on random numbers in JavaScript shows how to make random numbers with a seed.
For the broken glass, the demo puts 34 points close to the spot where you click or tap:
function getShardPoints(impactX, impactY) {
let points = [];
for (let i = 0; i < 34; i++) {
let angle = Math.random() * 2 * Math.PI;
let distance = 180 * Math.random() * Math.random();
points.push({
x: impactX + Math.cos(angle) * distance,
y: impactY + Math.sin(angle) * distance
});
}
return points;
}Every point is at most 180 pixels from the impact. Multiplying two random numbers gives more small numbers than big ones, so most of the points end up close to the impact. The demo also adds 10 more points at random spots across the window, so the parts far from the impact don't turn into a few huge shards.
Then getCell() cuts every shard out of the window. To do that, pass the window to getCell() as an extra argument, and have it start from the window's rectangle instead of one the size of the canvas. Some points land outside the window, and for those, getCell() can return an empty cell, so skip cells with fewer than 3 corners. Each shard gets a push away from the impact, and gravity pulls it down. The tutorial on collision detection and physics explains how to add gravity.
Common questions about Voronoi diagrams
How do I draw a Voronoi diagram on paper?
Start with two points, and draw their perpendicular bisector: the line that cuts the segment between them in half, at a right angle. Then add the other points one at a time. For each new point, draw the bisectors between it and the points around it, and erase the parts of the old lines that are now closer to the new point. A ruler and a compass help. Draw two circles of the same size, one centered on each point, big enough that they overlap. The bisector goes through the two spots where they cross.
What's the fastest algorithm for a Voronoi diagram?
Fortune's algorithm, from 1986, sweeps a line across the plane and builds the whole diagram in one go. The time it takes grows only a little faster than the number of points. It's tricky to get right, though. Most programs build a Delaunay triangulation with a fast algorithm instead. Then they build the cells from the triangles, as in the section about how Voronoi and Delaunay fit together. And on a graphics card, a shader can find the closest point for every pixel at the same time.
Should I use a library like Delaunator or d3-delaunay?
For a few hundred points, the code in this tutorial is fast enough, and you know exactly what it does. For thousands of points that move every frame, use a library. Delaunator, by Vladimir Agafonkin of Mapbox, triangulates 100,000 points in less than a tenth of a second. d3-delaunay, by Mike Bostock, builds on Delaunator and adds the Voronoi cells, clipped to a rectangle. Both are free to use, under the ISC license.
How do I find the neighbors of a cell?
Use the Delaunay triangulation: two points are neighbors if an edge of a triangle connects them. Go through the triangles, and for every corner, note the other two corners as its neighbors. Near the edges of the canvas, two points can be neighbors in the triangulation while the edge between their cells lies outside the canvas.
Why are the cells near the edges of the canvas so big?
There are no points beyond the edges to cut them off. In a real Voronoi diagram, the cells on the outside go on forever, and getCell() only stops them at the edges of the canvas. If you don't want big cells there, spread the points out evenly with Lloyd's algorithm. Or add a ring of extra points just outside the canvas, and don't draw their cells.
How do I make a Voronoi diagram that wraps around at the edges?
Copy the points eight times: to the left, to the right, above, below and diagonally toward each of the four corners. Move each copy by the width of the canvas, its height, or both. Build the cells with all the copies, and draw every cell that reaches into the canvas, in the color of its original point. Then a cell that runs off the right side continues on the left. That's handy for a texture that tiles, or a game world that wraps around.
What's the difference between a Voronoi diagram and Worley noise?
Worley noise is built on a Voronoi diagram. Instead of the cells, it uses the distance to the closest point, the second-closest point, or a mix of them, as a value for every pixel. That's what Distance map and Edges show in the section about measuring distance. Steven Worley came up with it in 1996, to make textures like stone and skin.
What is a weighted Voronoi diagram?
In a weighted Voronoi diagram, every point has a weight that makes its cell bigger or smaller. A common kind is the power diagram. In a power diagram, a heavier point pushes the edges away from itself, but the edges stay straight. You could use it to give a big city a bigger region on a map than a small one. Weighted Voronoi stippling is something else: in stippling, the pixels have the weights, not the points.
How do I let people use their own photo?
Add a hidden <input type="file" accept="image/*"> to your page, and have a button call its click() method. That opens the device's file picker. URL.createObjectURL() turns the file someone picks into an address that only exists in their browser, so the photo loads like any other image. Draw it on a canvas, and getImageData() gives you its pixels. The photo isn't uploaded unless your code sends it somewhere.
Where are Voronoi diagrams used in real life?
Wherever someone asks what's closest. Geographers use them to estimate the rainfall between weather stations. City planners use them to split a city into areas around schools, hospitals or fire stations. A robot can follow the edges of a Voronoi diagram to stay as far as possible from obstacles. Biologists see them in plant cells and animal territories, and designers use them for buildings, furniture and jewelry.
Is a Voronoi diagram the same as Thiessen polygons or a Dirichlet tessellation?
Yes, those names all describe the same thing, from different fields. Geographers call the cells Thiessen polygons, after the meteorologist Alfred Thiessen. Mathematicians also call the whole diagram a Dirichlet tessellation, after Peter Gustav Lejeune Dirichlet. The name Voronoi diagram comes from the mathematician Georgy Voronoi, who wrote about these diagrams in 1908.
Example code: a Voronoi diagram
Here's an example page that puts the basics from this tutorial together in a single HTML file. It draws the cells of 30 random points with getCell(), and you can drag the points around. The buttons show or hide the Delaunay triangulation, take one step of Lloyd's algorithm, and make new random points. Copy all of the code below into a new .html file and open that file in your browser:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Voronoi Diagram Tutorial | Spicy Yoghurt</title>
</head>
<body>
<h1>Voronoi diagram tutorial by Spicy Yoghurt</h1>
<canvas id="canvas" width="750" height="400" style="border:1px solid lightgray;">
Your browser does not support the HTML5 canvas tag.
</canvas>
<p>
<button id="triangles">Show triangles</button>
<button id="relax">Lloyd step</button>
<button id="new-points">New points</button>
</p>
<script>
'use strict';
let canvas;
let context;
let points = [];
let showTriangles = false;
let dragged = null;
const colors = [
[255, 192, 192],
[255, 216, 192],
[255, 231, 168],
[155, 228, 184],
[128, 204, 216],
[224, 192, 255],
[224, 202, 192]
];
window.onload = init;
function init() {
canvas = document.getElementById('canvas');
context = canvas.getContext('2d');
// So dragging a point doesn't scroll the page on a phone
canvas.style.touchAction = 'none';
points = createPoints(30);
canvas.addEventListener('pointerdown', startDrag);
canvas.addEventListener('pointermove', drag);
canvas.addEventListener('pointerup', stopDrag);
canvas.addEventListener('pointercancel', stopDrag);
let trianglesButton = document.getElementById('triangles');
trianglesButton.onclick = function () {
showTriangles = !showTriangles;
trianglesButton.textContent = showTriangles
? 'Hide triangles'
: 'Show triangles';
draw();
};
document.getElementById('relax').onclick = function () {
relax(points);
draw();
};
document.getElementById('new-points').onclick = function () {
points = createPoints(30);
draw();
};
draw();
}
function createPoints(count) {
let newPoints = [];
for (let i = 0; i < count; i++) {
newPoints.push({
x: Math.random() * canvas.width,
y: Math.random() * canvas.height,
color: colors[i % colors.length]
});
}
return newPoints;
}
// Keeps the part of the polygon that's closer to a than to b
function clipPolygon(polygon, a, b) {
let middleX = (a.x + b.x) / 2;
let middleY = (a.y + b.y) / 2;
let result = [];
for (let i = 0; i < polygon.length; i++) {
let p = polygon[i];
let q = polygon[(i + 1) % polygon.length];
// Below 0 is the side of a, above 0 the side of b
let sideP =
(p.x - middleX) * (b.x - a.x) +
(p.y - middleY) * (b.y - a.y);
let sideQ =
(q.x - middleX) * (b.x - a.x) +
(q.y - middleY) * (b.y - a.y);
if (sideP <= 0) {
result.push(p);
}
if ((sideP <= 0) != (sideQ <= 0)) {
let t = sideP / (sideP - sideQ);
result.push({
x: p.x + (q.x - p.x) * t,
y: p.y + (q.y - p.y) * t
});
}
}
return result;
}
function getCell(point, points) {
let cell = [
{x: 0, y: 0},
{x: canvas.width, y: 0},
{x: canvas.width, y: canvas.height},
{x: 0, y: canvas.height}
];
for (let other of points) {
if (other != point) {
cell = clipPolygon(cell, point, other);
}
}
return cell;
}
function drawCell(cell, color) {
context.beginPath();
context.moveTo(cell[0].x, cell[0].y);
for (let i = 1; i < cell.length; i++) {
context.lineTo(cell[i].x, cell[i].y);
}
context.closePath();
context.fillStyle = 'rgb(' + color.join(', ') + ')';
context.fill();
context.stroke();
}
function getCircumcircle(a, b, c) {
let d = 2 * (a.x * (b.y - c.y) + b.x * (c.y - a.y) +
c.x * (a.y - b.y));
let aa = a.x * a.x + a.y * a.y;
let bb = b.x * b.x + b.y * b.y;
let cc = c.x * c.x + c.y * c.y;
let x = (aa * (b.y - c.y) + bb * (c.y - a.y) +
cc * (a.y - b.y)) / d;
let y = (aa * (c.x - b.x) + bb * (a.x - c.x) +
cc * (b.x - a.x)) / d;
let dx = a.x - x;
let dy = a.y - y;
return {x: x, y: y, radiusSquared: dx * dx + dy * dy};
}
function isInCircle(point, circle) {
let dx = point.x - circle.x;
let dy = point.y - circle.y;
return dx * dx + dy * dy < circle.radiusSquared;
}
function createTriangle(a, b, c) {
return {
corners: [a, b, c],
circle: getCircumcircle(a, b, c)
};
}
// The Bowyer–Watson algorithm
function triangulate(points) {
// A triangle that's much bigger than the canvas, with its
// corners 100 million pixels away
let big = [
{x: -100000000, y: -100000000},
{x: 100000000, y: -100000000},
{x: 0, y: 100000000}
];
let triangles = [createTriangle(big[0], big[1], big[2])];
for (let point of points) {
let badTriangles = triangles.filter(function (triangle) {
return isInCircle(point, triangle.circle);
});
let hole = getHoleEdges(badTriangles);
triangles = triangles.filter(function (triangle) {
return !badTriangles.includes(triangle);
});
for (let edge of hole) {
triangles.push(
createTriangle(edge[0], edge[1], point)
);
}
}
return triangles.filter(function (triangle) {
return !triangle.corners.some(function (corner) {
return big.includes(corner);
});
});
}
function getHoleEdges(badTriangles) {
let edges = [];
for (let triangle of badTriangles) {
let [a, b, c] = triangle.corners;
edges.push([a, b], [b, c], [c, a]);
}
return edges.filter(function (edge) {
let count = edges.filter(function (other) {
return (other[0] == edge[0] && other[1] == edge[1]) ||
(other[0] == edge[1] && other[1] == edge[0]);
}).length;
return count == 1;
});
}
function getCentroid(polygon) {
let area = 0;
let x = 0;
let y = 0;
for (let i = 0; i < polygon.length; i++) {
let p = polygon[i];
let q = polygon[(i + 1) % polygon.length];
let cross = p.x * q.y - q.x * p.y;
area += cross;
x += (p.x + q.x) * cross;
y += (p.y + q.y) * cross;
}
area /= 2;
return {x: x / (6 * area), y: y / (6 * area)};
}
// One step of Lloyd's algorithm
function relax(points) {
let centers = points.map(function (point) {
return getCentroid(getCell(point, points));
});
points.forEach(function (point, i) {
point.x = centers[i].x;
point.y = centers[i].y;
});
}
function draw() {
context.clearRect(0, 0, canvas.width, canvas.height);
context.strokeStyle = '#303030';
context.lineWidth = 2;
for (let point of points) {
drawCell(getCell(point, points), point.color);
}
if (showTriangles) {
context.strokeStyle = '#0099b0';
for (let triangle of triangulate(points)) {
let [a, b, c] = triangle.corners;
context.beginPath();
context.moveTo(a.x, a.y);
context.lineTo(b.x, b.y);
context.lineTo(c.x, c.y);
context.closePath();
context.stroke();
}
}
context.fillStyle = '#303030';
for (let point of points) {
context.beginPath();
context.arc(point.x, point.y, 4, 0, 2 * Math.PI);
context.fill();
}
}
function getPointerPosition(event) {
let rect = canvas.getBoundingClientRect();
let scale = canvas.width / rect.width;
return {
x: (event.clientX - rect.left) * scale,
y: (event.clientY - rect.top) * scale
};
}
function startDrag(event) {
let position = getPointerPosition(event);
for (let point of points) {
let dx = point.x - position.x;
let dy = point.y - position.y;
// Grab a point within 20 pixels
if (dx * dx + dy * dy < 20 * 20) {
dragged = point;
canvas.setPointerCapture(event.pointerId);
}
}
}
function drag(event) {
if (dragged) {
let position = getPointerPosition(event);
// Keep the point on the canvas
let x = Math.min(position.x, canvas.width);
let y = Math.min(position.y, canvas.height);
dragged.x = Math.max(x, 0);
dragged.y = Math.max(y, 0);
draw();
}
}
function stopDrag() {
dragged = null;
}
</script>
</body>
</html>Conclusion
A Voronoi diagram gives every point a cell with all the spots that are closer to it than to any other point. You can draw one pixel by pixel, or cut each cell out of the canvas along the bisectors. Connect the neighbors, and you get the Delaunay triangulation, which you can build with the Bowyer–Watson algorithm. Lloyd's algorithm spreads the points out evenly. Add a photo, and the dots, cells and triangles become stipple art, stained glass and low-poly art.
That's all for now. If you have any questions, feel free to ask them in the comment section. Made something cool with a Voronoi diagram? Tell us about it in the comments. You can download the example code here.
Comments
Thanks! We've received your comment. We check every comment by hand before it appears, so this can take a few days.

No comments yet. Be the first to leave one!