Skip to content

Instantly share code, notes, and snippets.

@danharr
Last active August 29, 2015 14:00
Show Gist options
  • Save danharr/11193043 to your computer and use it in GitHub Desktop.
Save danharr/11193043 to your computer and use it in GitHub Desktop.
Understanding Voronoi diagram creation

Understand how Voronoi diagrams are formed by adding your own "seeds" to the above visual. The existing Voronoi diagram will continuously adjust as new seeds/sites are added. Click the visual to add new seeds!!

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>DIY Voronoi</title>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://d3js.org/topojson.v1.min.js"></script>
<style>
.voronoi {
fill: none;
stroke: #000000;
fill-opacity: 1}
</style>
</head>
<body>
<script type="text/javascript">
var svg = d3.select("body")
.append("svg")
.attr("width", 900)
.attr("height", 600);
var group = svg.append("g");
var data = [[100,200],[400,50]];
var projection = d3.geo.mercator()
.scale(7000)
.rotate([0,0,0]);
group.selectAll(".circles")
.data(data).enter().append("circle")
.attr("class","circles")
.attr("r",15)
.style("stroke","white")
.style("opacity",1)
.attr("cx",function(d) {return d[0];})
.attr("cy",function(d) {return d[1];});
svg.on("click",addCircle);
function addCircle() {
data.push(d3.mouse(this));
var voronoi = d3.geom.voronoi(data);
var pathFn = function(d) {
return "M" + d.join("L") + "Z"; };
svg.selectAll("path").remove();
svg.selectAll("path")
.data(voronoi)
.enter()
.append("path")
.attr("d", pathFn)
.classed("voronoi", true);
group.selectAll(".circles")
.data(data).enter().append("circle")
.attr("class","circles")
.attr("r",15)
.style("stroke","white")
.style("opacity",1)
.attr("cx",function(d) {return d[0];})
.attr("cy",function(d) {return d[1];});
};
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment