Fractal Tree
      
by ilyas usal

The following animation is the fractal tree that combines everything about recursion you have learned until this point:

[ a fractal tree ]

All right, so we have a pretty good start. The last thing we need to change to get a nice tree is the fact that each branch can spawn a bunch of baby branches. We are going to take care of that in a nice little for loop.

/*** Constants ***/
sub_branch = 3;
sub_angle = Math.PI/3;
max_size = 7;
branch_length = 50;
branch_length_dimin = .8;

/*** Function ***/
function makeBranch ( start_x, start_y, length, angle, size ) {
if ( size > 0 ) {
this.lineStyle ( size, 0x333333, 100 ) ;
this.moveTo ( start_x, start_y ) ;
var end_x = start_x + length * Math.cos ( angle ) ;
var end_y = start_y + length * Math.sin ( angle ) ;
this.lineTo (end_x, end_y) ;

if (sub_branch > 1) var inc_angle = sub_angle / (sub_branch - 1) ;
for ( var i=0; i < sub_branch; i++ ) {
var newLength = length * branch_length_dimin;
var newAngle = angle - sub_angle / 2 + i * inc_angle;
var newSize = size - 1 ;
makeBranch ( end_x, end_y, newLength, newAngle, newSize) ;
}
}
}

/*** Function call ***/
makeBranch ( 200, 200, branch_length, -Math.PI/2, max_size);

So, what did we do? First we defined a bunch of variables to edit the code more easily:

  • sub_branch
    number of sub-branches. We use that number in the for loop that creates the sub-branches
     
  • sub_angle
    maximum angle that the baby clips will be pointing to
     
  • max_size
    size of the tree, that is to say number of recursions, or branches
     
  • branch_length
    starting length of a branch
     
  • branch_length_dimin
    shrinking ratio of the baby branches

First we substituted those variables in the code to get something a bit more dynamic. That way, you can change a single variable to get a totally different tree.

if (sub_branch > 1) var inc_angle = sub_angle / (sub_branch - 1)

If we have more than 1 sub-branch, we calculate what I called inc_angle, which is the difference of angle between 2 sub-branches. It's a bit tricky, but you don't really need to understand it, just trust me. Then instead of creating one single sub-branch, we create as many as we want with a for loop.

Ilyas Usal
{Pictures 1 | 2}

 



SUPPORTERS:

kirupa.com's fast and reliable hosting provided by Media Temple.