p5.js is built on functions. For example, the draw()
loop is a function used in every sketch. All shapes are drawn using functions such as ellipse()
, rect()
and line()
.
As a reminder, you can define functions by writing:
function nameOfFunction (x, y, z){ // Do something when this function is called }
In the code above, x
, y
, and z
are variables that represent the function’s parameters. Parameters are a way to introduce variations into your functions. For example, let’s say you want to draw three clouds, but you want each cloud’s location and size to be different. To do this, you would need to write parameters for your makeCloud()
function. When you call the function, the variables get replaced with the specific values passed into that makeCloud()
function call.
Take a look at the cloud.js file to your right. See how the function’s parameters are used to create variations. Keep in mind that p5.js runs through the program line by line, from top to bottom. Every time the program reaches a makeCloud()
function call, the program jumps to the function definition outside of the draw()
loop.
Instructions
With this exercise, you will practice calling a function and passing parameters into it.
Open sketch.js. Inside the draw()
function and below the background()
function, call the function makeCircle()
, which is already defined in the sketch. Pass in the value 4 for the xPos
, 50 for the yPos
, and 600 for the circleSize
parameter.
Below the one you just called, write a new call to the makeCircle()
function. Pass in the value 0 for the xPos
, 200 for the yPos
, and 200 for the circleSize
parameter.
Below your second makeCircle()
function, write your last call to the makeCircle()
function. Pass in the value 100 for the xPos
, 200 for the yPos
, and 1 for the circleSize
parameter.