Created
November 29, 2015 20:36
-
-
Save sabotuer99/e48d1a2bb8f4c04e1052 to your computer and use it in GitHub Desktop.
Dragon Curve fractal in JavaScript for Khan Academy project
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
/* | |
The dragon curve drawn using an L-system. | |
variables : X Y | |
constants : F + − | |
start : FX | |
rules : (X → X+YF+), (Y → -FX−Y) | |
angle : 90° | |
Here, F means "draw forward", − means "turn left 90°", and + means "turn right 90°". X and Y do not correspond to any drawing action and are only used to control the evolution of the curve. | |
*/ | |
var dragonCurve = function(depth){ | |
//base case | |
if(depth === 0){return 'FX';} | |
var turtle = dragonCurve(depth - 1); | |
var newTurtle = ''; | |
for(var i = 0; i < turtle.length; i++){ | |
if(turtle.charAt(i) === 'X'){ | |
newTurtle += 'X+YF+'; | |
} | |
else if (turtle.charAt(i) === 'Y'){ | |
newTurtle += '-FX-Y'; | |
} | |
else { | |
newTurtle += turtle.charAt(i); | |
} | |
} | |
return newTurtle; | |
}; | |
var turtleDraw = function(text, startx, starty, length){ | |
var direction = 0; | |
var x = startx; | |
var y = starty; | |
for(var i = 0; i < text.length; i++){ | |
if(text.charAt(i) === 'F'){ | |
//'F', draw forward length in direction | |
var endx = x + length * Math.cos(direction * 0.017453292519); | |
var endy = y + length * Math.sin(direction * 0.017453292519); | |
var red = x/400 * 255; | |
var blue = y/400 * 255; | |
var green = (x + y + 300)/400 * 255; | |
stroke(red, green, blue); | |
line(x,y,endx,endy); | |
x = endx; | |
y = endy; | |
} | |
else if(text.charAt(i) === '-'){ | |
//'-' add 90 degrees to direction | |
direction += 90; | |
} | |
else if(text.charAt(i) === '+'){ | |
//'+' subtract 90 degrees from direction | |
direction -= 90; | |
} | |
} | |
}; | |
fill(0, 0, 0); | |
rect(0,0,width,height); | |
stroke(255, 0, 0); | |
//strokeWeight(3); | |
//line(0,0,400,400); | |
var dragon = dragonCurve(14); | |
turtleDraw(dragon,200,90,2); | |
/*High definition... runs kinda slow | |
var dragon = dragonCurve(16); | |
turtleDraw(dragon,90,150,1); | |
//*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment