Skip to content

Instantly share code, notes, and snippets.

@mango314
Created June 23, 2014 15:45
Show Gist options
  • Save mango314/7235dc309c930132f6a1 to your computer and use it in GitHub Desktop.
Save mango314/7235dc309c930132f6a1 to your computer and use it in GitHub Desktop.

Voronoi Tesselation

Move your mouse around

<!DOCTYPE html>
<meta charset="utf-8">
<style>
path {
stroke: #fff;
}
path:first-child {
fill: blue !important;
}
</style>
<body>
<div id="news"></div>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script>
var width = 350,
height = 350;
var vertices = d3.range(100).map(function(d) {
return [ (Math.random() + (d/10 >> 0) )* (width/10), (Math.random() + (d% 10) )* (height/10)];
});
var voronoi = d3.geom.voronoi()
.clipExtent([[0, 0], [width, height]]);
var svg = d3.select("#news").append("svg")
.attr("width", width)
.attr("height", height);
var path = svg.append("g").selectAll("path");
svg.append("image")
.attr("xlink:href", "https://dl.dropboxusercontent.com/u/17949100/prDataMeetup/wilson-1.png")
.attr("width", width)
.attr("height", height)
.style('opacity',0.25);
redraw();
function redraw() {
V = voronoi(vertices);
for(var k = 0; k < 100; k += 1){
svg.append("path")
.attr("d", polygon(V[k]))
.style('opacity',0.75)
.on('mouseover', function() {
d3.select(this)
.style('fill', '#0F0')
.style('opacity',0.75);
})
.on('mouseout', function() {
d3.select(this)
.style('fill', '#000')
.style('opacity',0.75);
})
.on('click', function() {
d3.select(this)
.style('fill', '#000')
.style('opacity',0.75);
});
}
}
function polygon(d) {
return "M" + d.join("L") + "Z";
}
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment