Skip to content

Instantly share code, notes, and snippets.

@alexmacy
Last active July 27, 2016 06:01
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 alexmacy/5f9ba684d2c9ec68392dee86ff9636bb to your computer and use it in GitHub Desktop.
Save alexmacy/5f9ba684d2c9ec68392dee86ff9636bb to your computer and use it in GitHub Desktop.
Voronoi Shuffling v3
license: gpl-3.0

I realized that the annoying reshaping transition was a result of the new polygon having more sides than the one it was transitioning from. This meant that rather than transition the side from somewhere along the path of the old polygon, it would transition from off screen. To solve this, I included a function that basically draws extra points on top of eachother to give the polygon more sides than necessary - you can't see them, but they're there if you inspect the elements.

The previous versions are here: Voronoi Shuffling v1 & Voronoi Shuffling v2

<!DOCTYPE html>
<meta charset="utf-8">
<head>
<style>
body {
margin: 0;
}
path {
fill-opacity: 0;
stroke: black;
}
</style>
<script src="//d3js.org/d3.v4.min.js"></script>
</head>
<body></body>
<script>
var width = window.innerWidth,
height = window.innerHeight;
var voronoi = d3.voronoi()
.size([width, height]);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
var pointCoords = [],
oldPointCoords = [];
getPointCoords();
var dots = svg.selectAll("circle")
.data(pointCoords)
.enter().append("circle")
.attr("r", 2)
.attr("transform", function(d) {return "translate(" + d[0] + ", " + d[1] + ")"})
var paths = svg.selectAll("path")
.data(voronoi(pointCoords).polygons())
.enter().append("path")
.attr("d", function(d) {return getPath(d);})
function getPointCoords() {
for (i=0; i<100; i++) {
oldPointCoords[i] = pointCoords[i];
pointCoords[i] = [Math.random() * width, Math.random() * height]
};
};
function getPath(points) {
var thisPath = "M" + points[0];
for (n=1; n<10; n++) {
if (n < points.length) {
thisPath += "L" + points[n];
} else {
thisPath += "L" + points[0]
}
}
return thisPath;
}
var reDraw = function() {
getPointCoords();
dots.data(pointCoords)
.transition().duration(3000)
.attr("transform", function(d) {return "translate(" + d[0] + ", " + d[1] + ")"})
paths.data(voronoi(pointCoords).polygons())
.transition().duration(3000)
.attr("transform", function(d, i) {return "translate(" + (pointCoords[i][0] - oldPointCoords[i][0]) + ", " + (pointCoords[i][1] - oldPointCoords[i][1]) + ")"})
.transition().duration(3000)
.attr("transform", "translate(0,0)")
.attr("d", function(d) {return getPath(d);})
d3.timeout(reDraw, 8000);
}
d3.timeout(reDraw, 2000);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment