Using p5 variables and functions outside setup and draw

Just making sure…

p5 variables such as width and height, and p5 functions such as rect() and fill() can be used outside setup() and draw() as long as they’re in a function that is called from within either setup() or draw()

right?

For example:


function setup() {
  createCanvas(600, 600);
  background(30);
}

function draw() {
  myRectangle();
}

function myRectangle() {
  fill(150);
  rect(width / 2, height / 2, 200, 200);
}

I mean I can see it works when I test it, and have done it all the time, but I’m wondering if there are any gotchas or situations in which it should be avoided or that we should be careful.

One thing I do know is that createCanvas() needs to be called first. But that’s true even when using the p5 variables and functions directly inside setup().

Before createCanvas(), width & height are both 100.

If a 100x100 canvas 2d is enough for your sketch, you don’t need to invoke createCanvas() at all!

Actually, they’re not variables, but field properties from class p5.

When using p5js in global mode, those properties can also be accessed via globalThis or window, like globalThis.width or window.height:

They’re also available via p5.instance, like p5.instance.width or p5.instance.height.

p5.instance becomes available just before callbacks like preload() or setup() are executed.

We can prematurely make p5.instance available by instantiating class p5 outside the functions like this: new p5;

3 Likes

Hello @slacle ,

You will find some useful resources and information here:
https://p5js.org/ < Check out the learn section!

There is a lot there to peruse but worthy of exploration.

:)