Simplified version of Christopher Manning's Voronoi diagram using D3.js.
Last active
August 29, 2015 14:12
-
-
Save codybuell/74995bfa9c7629690f7c to your computer and use it in GitHub Desktop.
Draggable Voronoi Geom
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<head> | |
<meta charset="utf-8"> | |
<style> | |
body { | |
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; | |
width: 960px; | |
height: 500px; | |
position: relative; | |
} | |
path { | |
stroke: #333; | |
fill: #ccc; | |
} | |
</style> | |
</head> | |
<body> | |
<script src="http://d3js.org/d3.v3.min.js"></script> | |
<script> | |
// define width and height of svg element | |
var w = 960, | |
h = 500; | |
// generate some random data points | |
var vertices = d3.range(50).map(function(d) { | |
return [Math.random() * w, Math.random() * h]; | |
}); | |
// setup voronoi geom | |
var voronoi = d3.geom.voronoi().x(function(d) { return d.x; }).y(function(d) { return d.y; }); | |
// not sure why but removing this breaks drag functionality | |
var zoom = d3.behavior.zoom().on("zoom", function(d,i) { | |
force.nodes(vertices).start(); | |
}); | |
// prepare svg element | |
var svg = d3.select("body") | |
.append("svg") | |
.attr("width", w) | |
.attr("height", h) | |
.call(zoom); | |
// setup the force | |
var force = d3.layout.force() | |
.charge(-800) | |
.size([w, h]) | |
.on("tick", update) | |
.nodes(vertices) | |
.start(); | |
// setup the path | |
var path = svg.selectAll("path"); | |
// make it happen | |
function update(e) { | |
path = path.data(voronoi(vertices)) | |
.attr("d", function(d) { return "M" + d.join("L") + "Z"; }); | |
path.enter().append("path") | |
.call(d3.behavior.drag() | |
.on("drag", function(d, i) { | |
vertices[i] = {x: vertices[i].x + d3.event.dx, y: vertices[i].y + d3.event.dy}; | |
}) | |
); | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment