Automatic Fractal
Branch
by
ilyas usal
Now I don't know what you think about all this, but so far, recursion has
been a pretty exhausting process for your fingers. That's why we are going to
forget about that manual recursion, and automate it.
[ just click once ]
The code for the above example is:
function makeBranch(start_x, start_y, length, angle, size) {
if (size>0) {
this.lineStyle(size, 0x1F3245, 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);
var
newLength = length*.8;
var newAngle = angle+Math.PI/16;
var newSize = size-1;
makeBranch(end_x, end_y, newLength, newAngle, newSize);
}
}
this.onMouseDown = function() {
makeBranch(100, 190, 50, -Math.PI/2, 10);
delete this.onMouseDown;
};
Here, instead of having the recursion code inside the onMouseDown handler, we
have incorporated it to the makeBranch function itself, thereby making it
recursive. We calculate the length, angle and size of the next branch, and then
draw that branch. The really big changes lies in the first line of code:
if ( size > 0
)
This is the condition we use to stop the loop: the size should be positive,
otherwise we don't get inside the loop, and no other branch is created. The
starting size is 10 (last parameter in the function call), so we'll create 10
baby branches. Simple :)
|
Ilyas Usal
{Pictures
1
|
2} |
|