Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

deutsche Version

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 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 processingp5js, functions that have no return value are declared with “void” “function” return type.

Function Declaration

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

...

functionName(parameter,.....) ;


Function Examples

This example shows how to write functions with return values.

void
Code Block
languagejs
linenumberstrue
function setup()
{
  const result = println(addition(1,2));
  println(addition(2,calculateSquare(4); // assign variable to call a function
  console.log(result);

  print(calculateSquare(10)); }// call function directly
int}
addition(int parameter1,
intfunction parameter2calculateSquare(x) {
  return parameter1x +* parameter2x;
}


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

void
Code Block
languagejs
function setup()
{
  sizecreateCanvas(500,300);
  stroke(255);
  strokeWeight(3);
  noFill();
}
 
voidfunction draw()
{
  background(0);
  smiley(100, height/2);
  smiley(250, height/2);
  smiley(400, height/2);
}
 
function void smiley(intx x, int y)
{
  printlnprint("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:

void
Code Block
languagejs
function setup()
{
  sizecreateCanvas(300,300);
background(0);
stroke(255);
backgroundstrokeWeight(010); 
}

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


voidfunction mousePressed()
{
  printlnprint("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).