public
Last active

Voronoi Tessellation

  • Download Gist
README.md
Markdown

The Voronoi tessellation shows the closest point on the plane for a given set of points. This example updates the Voronoi diagram in response to mouse interaction! Colors by Cynthia Brewer; algorithm by Steven Fortune; implementation based on work by Nicolas Garcia Belmonte; interaction inspired by Raymond Hill.

index.html
HTML
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
<!DOCTYPE html>
<meta charset="utf-8">
<style>
 
path {
stroke: #fff;
}
 
path:first-child {
fill: yellow !important;
}
 
circle {
fill: #000;
pointer-events: none;
}
 
.q0-9 { fill: rgb(197,27,125); }
.q1-9 { fill: rgb(222,119,174); }
.q2-9 { fill: rgb(241,182,218); }
.q3-9 { fill: rgb(253,224,239); }
.q4-9 { fill: rgb(247,247,247); }
.q5-9 { fill: rgb(230,245,208); }
.q6-9 { fill: rgb(184,225,134); }
.q7-9 { fill: rgb(127,188,65); }
.q8-9 { fill: rgb(77,146,33); }
 
</style>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
 
var width = 960,
height = 500;
 
var vertices = d3.range(100).map(function(d) {
return [Math.random() * width, Math.random() * height];
});
 
var voronoi = d3.geom.voronoi()
.clipExtent([[0, 0], [width, height]]);
 
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.on("mousemove", function() { vertices[0] = d3.mouse(this); redraw(); });
 
var path = svg.append("g").selectAll("path");
 
svg.selectAll("circle")
.data(vertices.slice(1))
.enter().append("circle")
.attr("transform", function(d) { return "translate(" + d + ")"; })
.attr("r", 1.5);
 
redraw();
 
function redraw() {
path = path
.data(voronoi(vertices), polygon);
 
path.exit().remove();
 
path.enter().append("path")
.attr("class", function(d, i) { return "q" + (i % 9) + "-9"; })
.attr("d", polygon);
 
path.order();
}
 
function polygon(d) {
return "M" + d.join("L") + "Z";
}
 
</script>

The voronoi() algorithm goes badly wrong if two points are coincident.

eg insert line 40: vertices[2] = vertices[1];

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.