Wednesday, May 28, 2014

Fractal Tree

We have two new concepts to cover in creating a fractal.

First - recursion.  We'll make a function which we enter, it calls itself, then it has a way to exit itself.  branch(length) does just that.  We start out with a length of 150 (the base of the tree) and decrease 'length' by 1/3 until it reaches 10, then we exit the recursive loop.

Next to cover is save() and restore().  We save() the state of the canvas (translation, rotation, values of stroke/fill, etc.), rotate the canvas, branch out, restore() to the original canvas setup, then do the same for the other side.





function drawShapes() {

    c.translate(w / 2, h);

theta=56, i=0;

branch(150);

}

function branch(length) {

c.moveTo(0,0);
c.lineTo(0,-length);
c.stroke();
    c.translate(0, -length);

    length *= 0.66;

    if (length > 10) {

        c.save();
        c.rotate(theta);
        branch(length);
        c.restore();

        c.save();
        c.rotate(-theta);
        branch(length);
        c.restore();

    }
}


If you need further clarification on recursion, check out what branch() does when we only have one block of code between save() and restore() below.  We see a single line that is formed by calling itself, using a shorted "length" which has been rotated then drawn.  When we have both blocks of code, we're just doing this same thing but for both sides and "branching out" from each end point means we double the number of end points per recursion.






No comments: