Skip to content

Instantly share code, notes, and snippets.

@gsluthra
Created August 20, 2012 07:10
Show Gist options
  • Star 17 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save gsluthra/3401766 to your computer and use it in GitHub Desktop.
Save gsluthra/3401766 to your computer and use it in GitHub Desktop.
Fractal Tree Generation using HTML5 Canvas and Random Numbers
<html>
<head>
<script type="text/javascript">
window.onload = draw;
function draw(){
var canvas = document.getElementById('myCanvas');
if (canvas.getContext){
var context = canvas.getContext('2d');
drawFractalTree(context);
}
else{
alert("HTML5 Canvas isn't supported by your browser!");
}
}
function drawFractalTree(context){
drawTree(context, 800, 800, -90, 11);
}
function drawTree(context, x1, y1, angle, depth){
var BRANCH_LENGTH = random(0, 20);
if (depth != 0){
var x2 = x1 + (cos(angle) * depth * BRANCH_LENGTH);
var y2 = y1 + (sin(angle) * depth * BRANCH_LENGTH);
drawLine(context, x1, y1, x2, y2, depth);
drawTree(context, x2, y2, angle - random(15,20), depth - 1);
drawTree(context, x2, y2, angle + random(15,20), depth - 1);
}
}
function drawLine(context, x1, y1, x2, y2, thickness){
context.fillStyle = '#000';
if(thickness > 6)
context.strokeStyle = 'rgb(139,126, 102)'; //Brown
else
context.strokeStyle = 'rgb(34,139,34)'; //Green
context.lineWidth = thickness * 1.5;
context.beginPath();
context.moveTo(x1,y1);
context.lineTo(x2, y2);
context.closePath();
context.stroke();
}
function cos (angle) {
return Math.cos(deg_to_rad(angle));
}
function sin (angle) {
return Math.sin(deg_to_rad(angle));
}
function deg_to_rad(angle){
return angle*(Math.PI/180.0);
}
function random(min, max){
return min + Math.floor(Math.random()*(max+1-min));
}
</script>
<style type="text/css">
canvas { border: 1px solid white; }
</style>
</head>
<body>
<canvas id="myCanvas" width="1500" height="800"></canvas>
</body>
</html>
@matthewd673
Copy link

Thanks for sharing, the code works well!

@jstoxrocky
Copy link

This is really awesome! Thanks :)

@p1nesap
Copy link

p1nesap commented Dec 25, 2014

Thanks for posting this easy to follow example. Great!

@atMari
Copy link

atMari commented Mar 14, 2015

Beautiful. I love it.

@ruffner
Copy link

ruffner commented Jun 27, 2016

Too cool! Wrapping the recursive calls in a setTimeout() yields a nice effect, as does setting the globalAplha on the canvas, I've found.

@ao
Copy link

ao commented Jun 11, 2018

Very nice

@Merteg
Copy link

Merteg commented Sep 13, 2018

Too cool! Wrapping the recursive calls in a setTimeout() yields a nice effect, as does setting the globalAplha on the canvas, I've found.

Also if you change depth from 1 to ~14 in setTimeout iterations, you can get an interesting animation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment