p5: Functions

This sketch draws a smiley


function setup()
{
  createCanvas(800, 800);
  background(255);
}
 
function draw()
{
  
  background(255);
  noStroke();
  fill("#ffcf67");
  ellipse(50, 50, 80, 80);
  fill("#7b6b47");
  ellipse(30, 40, 10, 10);
  ellipse(70, 40, 10, 10);
  noFill();
  stroke("#7b6b47");
  strokeWeight(3);
  arc(50, 50, 50, 50, radians(20), radians(160));
}

We can put the instructions in a function that can be reused multiple times. It makes the code more readable and “abstracts” the act of drawing a smiley:



function setup()
{
  createCanvas(800, 800);
  background(255);
}
 
function draw()
{
  drawSmiley();
}

function drawSmiley() {

  background(255);
  noStroke();
  fill("#ffcf67");
  ellipse(50, 50, 80, 80);
  fill("#7b6b47");
  ellipse(30, 40, 10, 10);
  ellipse(70, 40, 10, 10);
  noFill();
  stroke("#7b6b47");
  strokeWeight(3);
  arc(50, 50, 50, 50, radians(20), radians(160));

}

It’s not very useful right now.
We can add parameters (aka arguments) to generalize the house drawing function, making our code more flexible.
For example draw a smiley at a position x and y:


function setup()
{
  createCanvas(800, 800);
  background(255);
}
 
function draw()
{
  background(255);
  drawSmiley(mouseX, mouseY);
}


function drawSmiley(x, y) {
  
	push();
	translate(x, y);
	noStroke();
  fill("#ffcf67");
  ellipse(50, 50, 80, 80);
  fill("#7b6b47");
  ellipse(30, 40, 10, 10);
  ellipse(70, 40, 10, 10);
  noFill();
  stroke("#7b6b47");
  strokeWeight(3);
  arc(50, 50, 50, 50, radians(20), radians(160));
	pop();
}

Note how I moved the background(255); outside of the function to prevent a smiley call from clearing anything that has been drawn before.

Add parameters for color, rotation, and scale. One at a time.
Add a parameter for expression (eg sad face)
Arrange them in a grid using for loops.

Functions can also return a value. That value can be transferred to a variable through an assignment:

function setup()
{
  createCanvas(800, 800);
  background(255);
}
 
function draw()
{
  background(255);
  var radius = 100;
  var diameter = findDiameter(radius);
  
  ellipse(400, 400, diameter, diameter);
}


function findDiameter(r) {
  var d = r * 2;
  return d;
}

Now try to reproduce the plotter drawing below and then replace squares with something drawn with a function


(Georg Nees Schotter, 1968)