Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 5 Next »


Syntax of functions

There are two parts of a function. First there is the the function declaration, where the name of the function along with its properties and behaviors are defined. Next there is the function call, where the function is then actually executed. Functions may be called multiple times.

Functions can also accept input values (called parameters) that are sent to the function when called. These input parameters can change the behaviour of the function.

Functions can also return a value. This means when we return to the line where the function was called, it has now carried a number with it. In p5js, functions that have no return value are declared with “function” return type.

Function Declaration

This is how the function is named, its return type and parameters defined with sudo code.


datatype functionName (parameter,.....)

{

<function contents>

<possible return value>

}


Function call 

This is how we execute a function:

functionName(parameter,.....) ;


Function Examples

This example shows how to write functions with return values.

function setup()
{
  const result = calculateSquare(4); // assign variable to call a function
  console.log(result);

  print(calculateSquare(10)); // call function directly
}
 
function calculateSquare(x) {
  return x * x;
}


This example shows how to use functions for creating legible and simple blocks (modularization).

function setup()
{
  createCanvas(500,300);
  stroke(255);
  strokeWeight(3);
  noFill();
}
 
function draw()
{
  background(0);
  smiley(100, height/2);
  smiley(250, height/2);
  smiley(400, height/2);
}
 
function smiley(x , y)
{
  print("smiley");
  ellipse(x, y, 100, 100);  // head
  
  ellipse(x - 20, y - 10, 10, 15);  // left eye
  ellipse(x + 20, y - 10, 10, 15);  // right eye
   
  arc(x, y, 60, 60, radians(20), radians(180-20));  // mouth
}


And here is our first interactive program:

function setup(){
 createCanvas(300,300);
 background(0);
 stroke(255);
 strokeWeight(10); 
}

function draw(){
 point(mouseX, mouseY);
}

function mousePressed(){
 print("x:" + mouseX + ", y:" + mouseY);
 clear();
 background(0);
}

Exercise 4

Write a sketch where a unique shape follows the mouse position. When you click the mouse, the shape should change in some way (form, colour, size).