Skip to content

Top‐Level Global Mode

Quinton Ashley edited this page Nov 22, 2024 · 7 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-q2d : Top-Level Global Mode

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

new Q5();
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 at the same time!

new Q5();
createCanvas(200, 200);

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

function setup() {
  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 new Q5() is run before the sketch starts.

q5-webgpu : Top-Level Global Mode

Use of top level global mode with the WebGPU renderer requires that you make your sketch file a js module and await for Q5.webgpu() to return a Q5 instance (q), which you can then use to set q5 functions such as draw.

<script type="module" src="sketch.js">
let q = await Q5.webgpu();

createCanvas(200, 200);
noStroke();

q.draw = () => {
  clear();
  rect(50, 50, 100, 100);
};

This is because GPU.requestAdapter and GPUAdapter.requestDevice are async functions and a GPUDevice is needed before anything can be drawn to the canvas. The async function Q5.initWebGPU can perform this task without creating a Q5 instance.