Skip to content

Top‐Level Global Mode

Quinton Ashley edited this page Oct 19, 2025 · 11 revisions

In p5, functions like rect can't be used on the file level. They must be called from within p5 functions like setup and draw.

q5 Canvas2D : Top-Level Global Mode

In q5, existing p5 sketches that use setup and draw don't require modification. But if you create a Q5 canvas at the top of your sketch, the preload and setup functions become optional.

createCanvas(200, 200);

noStroke();
fill(0, 126, 255, 102);
rect(50, 50, 100, 100);

This is great because you don't have to declare variables on the file level and then define them in preload or setup. You can declare and define them on the same line!

Running createCanvas on the top level, it creates a new global instance of Q5 and a canvas.

createCanvas(200);

let cow = loadImage('cow.png');

function draw() {
  image(cow, 0, 0);
}

Note that if you use loadImage on the file level, q5 will wait to run setup and draw until the image loads.

Optionally if you forgo defining preload, you can run it to signify that the sketch can start once loading is complete. Otherwise q5 will auto-start the sketch after 32ms of delay, this ensures code after createCanvas() is run before the sketch starts.

q5 WebGPU : Top-Level Global Mode

See the "Module Usage" section:

https://github.com/q5js/q5.js/wiki/q5-WebGPU-renderer/#module-usage

Clone this wiki locally