Skip to content

Instantly share code, notes, and snippets.

@mbostock
Created March 29, 2016 17:49
Show Gist options
  • Save mbostock/50a8a5733b45c6287f7d32e3ac3241c4 to your computer and use it in GitHub Desktop.
Save mbostock/50a8a5733b45c6287f7d32e3ac3241c4 to your computer and use it in GitHub Desktop.
Voronoi Spirals II
height: 960
license: gpl-3.0
<!DOCTYPE html>
<meta charset="utf-8">
<canvas width="960" height="960"></canvas>
<script src="https://d3js.org/d3.v4.0.0-alpha.28.min.js"></script>
<script>
var canvas = d3.select("canvas").node(),
context = canvas.getContext("2d"),
width = canvas.width,
height = canvas.height;
var sites = d3.range(100).map(function() { return [Math.random() * width, Math.random() * height]; }),
cells = d3.voronoi().size([width, height]).polygons(sites),
duration = 5000;
var color = d3.scaleCubehelix()
.domain([duration, 0]);
var timer = d3.timer(function(elapsed) {
context.beginPath();
cells.forEach(function(cell) {
drawCell(cell);
var p0 = cell.shift(),
p1 = cell[0],
t = Math.min(0.5, 4 / distance(p0, p1)),
p2 = [p0[0] * (1 - t) + p1[0] * t, p0[1] * (1 - t) + p1[1] * t];
cell.push(p2);
});
context.fillStyle = color(elapsed);
context.fill();
if (elapsed > duration) timer.stop();
});
function drawCell(cell) {
context.moveTo(cell[0][0], cell[0][1]);
for (var i = 1, n = cell.length; i < n; ++i) context.lineTo(cell[i][0], cell[i][1]);
context.closePath();
}
function distance(a, b) {
var dx = a[0] - b[0], dy = a[1] - b[1];
return Math.sqrt(dx * dx + dy * dy);
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment