The Fractal Tree


Explore the use of recursive functions with this elegant and interactive fractal figure - the Fractal Tree.

To see a working example click here


Directions
  1. Set up your HTML page, insert the P5.js source tags into the <head>section of your project page:

    <script src= "https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.0/p5.js"></script>

    <script src= "http://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.6/addons/p5.dom.js"></script>

    Your code now speaks P5!

  2. In the setup function, create a canvas and draw a "trunk" line, 100 or so pixels long, from the bottom center of the screen.

  3. Now, lets setup your recursive function. A branch is a line (or branch) with two branches extending off the top to the right and left. As you can see, its a recursive definition.

    You should create a function called, say, drawBranch(), that, given an X and Y position as a starting point and branchLength, draws one branch to one side, at an angle branchAngle. To do this right, you will need to use a bit of trigonometry. Remember "SohCahToa"!

    HINT: the Math.sin function takes an angle in radians, not degrees.

    Call the function to draw one branch from the top of the trunk.

  4. Now create more branches to the same side by adding a call in the drawBranch() function to itself, using a new X and Y and making branchLength smaller for each iteration. This is Recursion!

  5. Your first recursive loop may have gone on too long and produced a "maximum call-stack exceeded" error. Add an exit condition check to stop the loop when branchLength is smaller than some number, say minBranchLength .

  6. Now add another variable, angleAdjust. This is how much the angle should change with each iteration. Modify your drawBranch() function to change the angle by this amount. Does your brach now curve?

  7. Write a function to clear the canvas.

  8. Add a button on top of the page above the canvas, that, when clicked, increases angleAdjust. You will need to clear the canvas, increase angleAdjust and redraw your tree. Once it works, display the angleAdjust variable on the page, and add a minus button to reduce angleAdjust.

  9. Add a counter to track how many branches are in your tree and show it on the screen.

    Your tree project should now look like this.

  10. Now go full-tree. Add a second recursive call to drawBranch() that curves in the opposite direction. This will create a second branch on top of every branch. Run it to see the whole tree. NOTE: it will take a bit more time to run and draw the tree.

  11. Add leaves to your tree. Make it so when length gets below a certain number, change branch color to be green.

  12. Add a variable by which to decrease branchLength in each generation, called branchGrowth . Add buttons to let the user modify the minBranchLength and the branchGrowth variables.

  13. Test and finish the project till it looks perfect to you.





(c) 2018 by Code Craft Academy