Designing Reusable Code - Overview
Applying Functions
Applying the Target Function
Applying the weirdShape Function-
Refactor With Functions
Create terse code using functions
-
Assignment Assistance
Last minute help with your assignments
Functions
A function is a self-contained module of code that can be reused. A helpful analogy for us as designers is to think of it as a template written in a way to be repeated.
You’ve been using the functions included with P5 such as
size()
,
line()
, and
stroke()
to write your programs, but it’s also possible
to write your own functions to reuse code.
Functions make code more concise by extracting the common elements and making them into code blocks that can be run many times within the program. This makes the code easier to read and update and reduces the chance of errors.
Parameters
Functions can take no parameters, or they can take multiple parameters that modify their actions. Parameters are defined for functions inside round brackets after their name.
Functions can be defined with different numbers of parameters, functions can behave different with a different number of parameters
createCanvas(1000, 1000);
fill(grayscale);
fill(red, green, blue);
fill(red, green, blue, alpha);
Return Values
Functions may provide a value when they complete whatever task
it is that they do, we call this the return value. Examples of
functions that return values include the
random()
and the
sin()
functions that
return values calculated based on parameters passed to them.
When a function is defined it will define the type of the values
it returns. For example, one variant of the
random()
function is defined as:
random(low, high)
Meaning that it takes takes two values and returns a decimal value when it is done.
Here were calling
random(10,20);
Writing Your Own Functions
To write our own functions, we need to know how to declare a function. The general form of a function is:
Parameters can be any input that can be put into a varaible. We can create functions to perform all kinds of tasks. In general, we create functions to structure our code so that it becomes easier to read and improve consistency across our sketch.
function functionName(parameters) {
statements
}
// We can also have mulitple parameters
function functionName(parameter1,parameter2,parameter3) {
statements
}
Returning Values with your own functions
The keyword
return
is used to exit a function and
return to the point in the program from which it was called.
When a function outputs a value, return is used to specify what value should be returned. The return statement is typically the last line of a function because functions exit immediately after a return. If a function returns a value, the function almost always appears to the right of an assignment operator or as a part of a larger expression.
A function that does not return a value is often used as a complete statement. If a function’s return value is not used immediately, or assigned to a variable, the value will be lost.
// Our function takes a parameter called spacing
function posX(spacing) {
// we can see it here being used to create a
// margin for random numbers
let x = random(spacing, width-spacing);
return x;
}
Writing Your Own Functions which return values
Here is an example where there is a funciton being used as tool to help us get random values bewteen a range. This may be helpful if we are repeating this type of funciton several times.
function setup() {
createCanvas(windowWidth, windowHeight);
rectMode(CENTER);
}
function draw() {
background(230);
// our funciton xPos is being called with a spacing of 100
ellipse(posX(100), height/2, 100);
rect(posX(100), height/2, 100,100);
noLoop();
}
// Our function takes a parameter called spacing
function posX(spacing) {
// we can see it here being used to create a
// margin for random numbers
let x = random(spacing, width-spacing);
return x;
}
Writing Your own functions which draw to canvas
Here is a custom function that draws a target shape with a few custom parameters to create a target shape. We have all of the drawing function and styles commands within the function. With this function we can create a target, dictate it's x and y coordinate on the canvas, the radius and the number of stripes within the target. Structuring sketches with appropriate functions like this allow for us to have terse code that creates consistent results.
function target(xPos, yPos, size, circleNum) {
noStroke();
for(let i = 0; i < circleNum; i++) {
// every second loop alternate the color of the ellipse
if(i % 2 == 0) {
fill(255);
} else {
fill(0);
}
// Calculate the size of the ellipse needed in each loop
let currentSize = size - i*size/circleNum;
ellipse(xPos, yPos, currentSize);
}
}
Creating custom shapes in P5.js
We can create custom shapes using three functions together
beginShape
,
vertex
and
endShape
. This is fairly basic example, check the
referece for more ways to work with
beginShape
function setup() {
createCanvas(windowWidth, windowHeight);
}
function draw() {
background(230);
let xPos = mouseX;
let yPos = mouseY;
noStroke();
fill(50);
beginShape();
// this point is controled by the mouse
vertex(xPos, yPos);
vertex((width/4)*3, height/4);
vertex(width/4, height/4);
endShape(CLOSE);
}
weirdShape Function
This is a small function that produces a random shape every time
it is called. We can see that it requires 4 parameters
xPos
,
yPos
,
size
and
points
.
function weirdShape(xPos, yPos, size, points) {
// style functions
fill(50);
noStroke();
// We are telling p5.js that we are going to create a new shape
beginShape();
// Here we are starting a for loop which defines how many points we are going to have
for(let i = 0; i < points; i++) {
// These vertexes will be based off the xPos and yPos we give it then
// it will devate by a random number by size in either direction
vertex(xPos + random(-size,size),yPos + random(-size,size));
}
// After all the random vertexes are drawn we say that the custom shape is complete
// Then it is draw to the actual canvas
endShape();
}
Refactoring Functions
functions often can become a requirement for neat and readable code when you start developing a sketch. If you find yourself repreating yourself this may be an opportinty to create a funciton to tidy things up. Additionally we can use funcitons centralise code so we only have to edit a few lines of code instead of several.
Here we can see a side by side of code where there is an opportinty to create a small function to shorten the code.
function setup() {
createCanvas(windowWidth, windowHeight);
rectMode(CENTER);
}
function draw() {
background(230);
// We can see here that there is an opporunity to make this code a bit neater
let random1 = random(100, width-100);
ellipse(random1, height/2, 100);
let random2 = random(100, width-100);
rect(random2, height/2, 100,100);
noLoop();
}
function setup() {
createCanvas(windowWidth, windowHeight);
rectMode(CENTER);
}
function draw() {
background(230);
ellipse(posX(100), height/2, 100);
rect(posX(100), height/2, 100,100);
noLoop();
}
// Our function takes a parameter called spacing
function posX(spacing) {
// we can see it here being used to create a
// margin for random numbers
let x = random(spacing, width-spacing);
return x;
}
Assignment Questions
Remember the assignment is due next Monday at 11:59pm!