p5art

Variables

In p5, a variable is a placeholder to store any value.

We declare a variable using the word let.

This line declares a new variable called circSize.

let circSize;

We can assign a value to the variable using a = sign.

circSize = 30;

But we don’t say “circSize equals 30”. We would say “circSize gets assigned to 30.”

We can declare and assign in a single line! This is VERY common!

let circSize = 30;

Once a variable is declared, it can be used over and over again.

let circSize = 30;
ellipse(20, 20, circSize, circSize);
ellipse(50, 50, circSize, circSize);
ellipse(80, 80, circSize, circSize);
ellipse(110, 110, circSize, circSize);

diagonal circles

By changing the value of the variable once, it changes everywhere that it is used!

let circSize = 50;

more diagonal circles

A variable can hold any type of data, not just numbers! This code would store text, called a String value, and use it to display text to the canvas.

let name = "Adam";
text(name, 20, 20);

Built-in Variables

p5 creates a lot of useful variables once a sketch is started!

Here are some examples…

We can use this variables anywhere inside draw. For example this code will always draw a line from (0,0) to the mouse location.

line(0, 0, mouseX, mouseY);

line example