Last active
February 20, 2016 11:19
-
-
Save robinhouston/a56ec5ef2cd4dc18dbc9 to your computer and use it in GitHub Desktop.
Hilbert curves
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
height: 512 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!doctype html> | |
<html> | |
<head> | |
<meta charset="utf-8"> | |
<title>Hilbert curve</title> | |
<script src="//d3js.org/d3.v3.min.js" charset="utf-8"></script> | |
<style> | |
svg path { fill: none; stroke: black; } | |
</style> | |
</head> | |
<body> | |
<div></div> | |
<script> | |
var ITERATIONS = 7; | |
var N = Math.pow(2, ITERATIONS + 2); | |
var svg = d3.select("div").append("svg") | |
.attr("width", 960).attr("height", N); | |
var path = svg.append("path"); | |
var s, i, n; | |
function next() { | |
s = s.replace(/([LR])/g, function(x) { | |
return ({L: "+RF-LFL-FR+", R: "-LF+RFR+FL-"})[x]; | |
}).replace(/-\+|\+-|\+\+\+\+|----/g, ""); | |
i++; | |
n *= 2; | |
} | |
function curve() { | |
var scale = N / n; | |
var r = "M" + (scale/2) + "," + (scale/2); | |
var b = [scale, 0]; | |
for (var j=0; j<s.length; j++) { | |
switch(s.charAt(j)) { | |
case '+': b = [ -b[1], b[0] ]; break; | |
case '-': b = [ b[1], -b[0] ]; break; | |
case 'F': | |
r += "l" + b[0] + "," + b[1]; | |
break; | |
} | |
} | |
return r; | |
} | |
function animate() { | |
next(); | |
path.transition().duration(2000) | |
.attr("d", curve()); | |
if (i < ITERATIONS) setTimeout(animate, 2500); | |
else setTimeout(reset, 4500); | |
} | |
function reset() { | |
s = "L"; | |
i = 0; | |
n = 1; | |
next(); | |
path.attr("d", curve()); | |
setTimeout(animate, 2000); | |
} | |
reset(); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment