Skip to content

Instantly share code, notes, and snippets.

@kraftner
Forked from mbostock/.block
Last active January 26, 2016 14:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kraftner/fea754a3dd36df736403 to your computer and use it in GitHub Desktop.
Save kraftner/fea754a3dd36df736403 to your computer and use it in GitHub Desktop.
Voronoi Tessellation
<!DOCTYPE html>
<meta charset="utf-8">
<style>
* {
margin:0;
padding:0;
}
body {
background-color: rgba(255,255,255,0.8);
}
path:first-child {
fill: #2d2d2a !important;
}
circle {
pointer-events: none;
}
path {
fill: rgba(255,255,255,0.1)
}
</style>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<script>
var width = Math.max(960, innerWidth),
height = Math.max(500, innerHeight);
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("d", polygon);
path.order();
}
function polygon(d) {
return "M" + d.join("L") + "Z";
}
window.addEventListener('message',function(e) {
e.source.postMessage('ready:' + e.data,e.origin);
svg.on("click", function() { e.source.postMessage(e.data,e.origin); });
},false);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment