Skip to content

Instantly share code, notes, and snippets.

@danreeves
Created April 24, 2014 16:13
Show Gist options
  • Save danreeves/11260293 to your computer and use it in GitHub Desktop.
Save danreeves/11260293 to your computer and use it in GitHub Desktop.
fractal tree
// canvas element and 2D context
var canvas = document.createElement( 'canvas' ),
ctx = canvas.getContext( '2d' );
canvas.width = 800;
canvas.height = 600;
document.body.appendChild(canvas);
ctx.translate(400,600);
branch(150, 0);
function branch (len, angle) {
ctx.save();
ctx.rotate(angle * Math.PI/180)
ctx.beginPath();
ctx.lineWidth = 1;
ctx.strokeStyle = 'black';
ctx.moveTo(0, 0);
ctx.lineTo(0, -len);
ctx.stroke();
ctx.translate(0, -len)
if (len > 5) {
branch(len*randomRange(0.7, 0.8), randomRange(10, 50));
branch(len*randomRange(0.7, 0.8), -randomRange(10, 50));
}
ctx.restore()
}
function randomRange(min, max) {
return (min + (Math.random()* (max-min)));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment