3:4 System variables

System variables in p5.js are variables that store information about things like the canvas width and height, or the x and y position of the mouse. They're really useful.

Using system variables

Often you don't know how big the canvas is, for instance if you use windowWidth and windowHeight instead of numerical values for the canvas then its impossible to know in advance where the edge of the canvas is. However the system variables width and height in p5.js will do this for you. Lets have a look:

// this will size the canvas to your browsers width & height
// then it will draw a circle right in the center.

function setup() {
  createCanvas(windowWidth, windowHeight);
  circle(width/2, height/2, 100)
}

Improving our animation

By using an additional variable for the circle radius and system variables to help determine its position we can vastly improve the animation.

The circle function in p5 takes x, y and diameter. However because circles draw fromt the center we are going to store its radius in a variable to start it just off screen, then loop when the end of the circle leaves the screen.

In this example the initial value of x is -radius (i.e. negative one radius to push it to the left). Then in the if statement we wait till x is the width + the radius before resetting it.