This is a simple script for generating a Dragon Curve.
Last active
November 13, 2015 23:01
-
-
Save omnizach/9f86cfa7443eb079b4f3 to your computer and use it in GitHub Desktop.
Dragon Curve.
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"> | |
<style> | |
</style> | |
</head> | |
<body> | |
<script src="http://d3js.org/d3.v3.min.js"></script> | |
<script> | |
var step_length = 1; | |
var iteration = 16; | |
var colors = ['#000000','#404040','#808080','#c0c0c0']; | |
function dragon_turn(n) { | |
return (((n & -n) << 1) & n) != 0; | |
} | |
function dragon_direction(n, v) { | |
return dragon_turn(n) ? (v == 0 ? 3 : v-1) : (v+1) % 4; | |
} | |
function dragon_curve(iteration) { | |
result = []; | |
v = 0; | |
result.push(v); | |
for (var i = 1; i < (1 << iteration); i++) { | |
v = dragon_direction(i, v); | |
result.push(v); | |
} | |
return result; | |
} | |
function dragon_curve_path(iteration, step_length) { | |
var result = 'M 0,0 '; | |
var path_commands = ['v ' + step_length + ' ', 'h ' + step_length + ' ', 'v -' + step_length + ' ', 'h -' + step_length + ' ']; | |
var directions = dragon_curve(iteration); | |
for (var i = 0; i < directions.length; i++) { | |
result += path_commands[directions[i]]; | |
} | |
return result; | |
} | |
var dragon_path = dragon_curve_path(iteration, step_length); | |
var svg = d3.select('body').append('svg') | |
.attr('width', 400) | |
.attr('height', 800) | |
.selectAll('g') | |
//.data([0,1,2,3]) | |
.data([0]) | |
.enter() | |
.append('g') | |
.attr('transform', function(d) { return 'translate(200,200) rotate(' + (d*90) + ')'; }) | |
.append('path') | |
.attr('d', dragon_path) | |
.attr('stroke', function(d) { return colors[d]; }) | |
.attr('stroke-linecap', 'square') | |
.attr('stroke-linejoin', 'miter') | |
.attr('fill', 'none'); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment