This is an archived tutorial from the kirupa.com legacy collection. It covers software that may no longer be available, but it is kept online because the ideas still hold up.
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:
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} |
Just a final word before we wrap up. What you've seen here is freshly baked content without added preservatives, artificial intelligence, ads, and algorithm-driven doodads. A huge thank you to all of you who buy kirupa's books, became a paid subscriber, watch the videos, and/or interact on the forums.
Your support keeps this site going! 😇
:: Copyright KIRUPA 2026 //--