Skip to content

Instantly share code, notes, and snippets.

@nategood
Last active August 29, 2015 14:02
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 nategood/64160cdcba940bbd17a6 to your computer and use it in GitHub Desktop.
Save nategood/64160cdcba940bbd17a6 to your computer and use it in GitHub Desktop.
Voronoi + Clip Path Fun
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
html, body {
margin: 0; padding: 0;
}
path.v {
fill-opacity: .1;
stroke-width: 0;
}
path.v:hover {
fill-opacity: .5;
stroke-width: 1px;
stroke-opacity: .7;
}
circle {
stroke-width: 0;
}
</style>
</head>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var padding = 0,
width = 960; //window.innerWidth,
height = 500; //window.innerHeight;
var points = [];
var amt = 25;
for (var i = 0; i < amt; i++) {
var w = Math.floor(Math.random() * (width - padding)),
h = Math.floor(Math.random() * (height - padding));
points.push([w, h]);
}
var voronoi = d3.geom.voronoi()
.clipExtent([[padding, padding], [width - padding, height - padding]]);
var color = d3.scale.category20();
// var color = d3.scale.linear()
// .domain([0, points.length])
// .range(["#ccc", "#333"]);
var svg = d3.select("body").append("svg")
.style("background", "#fff")
.attr("width", width)
.attr("height", height);
var defs = svg.append("defs");
svg.selectAll("path")
.data(voronoi(points))
.enter().append("path")
.attr("class", "v")
.style("fill", function(d, i) { return color(i); })
.style("stroke", function(d, i) { return color(i); })
.attr("d", function(d) { return "M" + d.join("L") + "Z"; });
defs.selectAll("clipPath")
.data(voronoi(points))
.enter()
.append("clipPath")
.attr("id", function(d, i) { return "cp-" + i; })
.append("path")
.attr("d", function(d) { return "M" + d.join("L") + "Z"; })
.attr("transform", function(d, i) { return "translate(-" + points[i][0] + ", -" + points[i][1] + ")"});
svg.selectAll("circle")
.data(points)
.enter().append("circle")
.style("fill", function(d, i) { return color(i); })
.attr("clip-path", function(d, i) { return "url(#cp-" + i + ")"; })
.attr("transform", function(d) { return "translate(" + d + ")"; })
.attr("r", 50);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment