|
- 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!
- In the setup function, create a canvas and draw a "trunk" line, 100 or so pixels long, from the bottom center of the screen.
- 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.
- 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!
- 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
.
- 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?
- Write a function to clear the canvas.
- 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.
- 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.
- 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.
- Add leaves to your tree. Make it so when length gets below a certain number, change branch color to be green.
- 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.
- Test and finish the project till it looks perfect to you.
|
|