Functions

This draws a house:

[js]
function setup()
{
createCanvas(600, 600);
background(255);

}

function draw()
{
triangle(15, 0, 0, 15, 30, 15);
rect(0, 15, 30, 30);
rect(12, 30, 10, 15);
}
[/js]

We can put the instructions in a function that can be reused multiple times and makes the code more readable:

[js]
function setup()
{
createCanvas(500, 500);
background(255);
}

function draw()
{
house();
}

function house()
{
triangle(15, 0, 0, 15, 30, 15);
rect(0, 15, 30, 30);
rect(12, 30, 10, 15);
}
[/js]

We can add parameters (aka arguments) to generalize the house drawing function making our code more flexible:

[js]
function setup()
{
createCanvas(500, 500);
background(255);
}

function draw()
{
background(255);
house(mouseX, mouseY);
}

function house(x, y)
{
triangle(x + 15, y, x, y + 15, x + 30, y + 15);
rect(x, y + 15, 30, 30);
rect(x + 12, y + 30, 10, 15);
}
[/js]

Posted in