|
- 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 set your background color to something light.
- Lets start by drawing a simple tree. First draw a trunk using the line() function. Place the tree in the screen's center. Once you have your trunk, add leaves using the ellipse() function. Give your trunk and leaves appropriate colors. Does your tree look good?
- Now lets convert this simple tree into a Tree class. To start, your Tree will just have a method, called show() that will hold the code you just wrote to draw the tree. class is the keyword to declare a Class, the same way you use var to declare a variable!
class Tree {
show() {
// Put your code for drawing the trunk and leaves here
}
}
- With our Tree class in hand, we can create a new tree easily using the new keyword. Try creating a tree (call it myFirstTree) in the setup() section. Then call its show() method to put it on the screen. (HINT: look at the Cat class for an example.)
- Now let's give our tree some additional properties. We can do that by adding a constructor() method to your Tree. A class's constructor is called everytime a new instance of the class, such as a new tree, is created. Lets start with x and y positions for the tree, a leafColor, and a size.
Note that the x and y values are passed as arguments to your Tree class when you call new to create it. They are then converted to properties in the constructor.
class Tree {
constructor(x, y) {
// Use the syntax: this.property = YOUR CODE
// Look at the Cat example for help.
// Convert the x and y arguments into properties here
// Generate a leafColor property
// Set the size property (this.size =)
}
show() {
// Change your trunk and leaf code to use the new Tree properties
}
}
Dont forget to update your new Tree call in the setup() section.
- Now change this call to use random values for the x and y. Does your tree appear with a different color and in a different place every time you refresh the screen?
- Now lets turn your Tree class into a forest! In the setup() section, create 50 trees at random positions to generate your forest!
- Continue to edit your code until it is readable, tidy, and you are satisfied. Have fun!!
|
|