### setup Source: https://github.com/q5js/q5.js/blob/main/_autodocs/api-reference/input-control.md Called once when the program starts, before the draw loop. Use to set initial canvas, variables, and settings. ```APIDOC ## setup ### Description Called once when the program starts, before the draw loop. Use to set initial canvas, variables, and settings. ### Method Function ### Parameters None ### Returns `void` ### Notes - Automatically called during initialization - Code runs once, not every frame ### Example ```javascript q5.setup = function () { createCanvas(400, 300); background('white'); }; ``` ``` -------------------------------- ### Initialize Canvas and Background Source: https://github.com/q5js/q5.js/blob/main/_autodocs/api-reference/input-control.md Use the setup function to initialize the canvas size and set the initial background color. This code runs once when the program starts. ```javascript q5.setup = function () { createCanvas(400, 300); background('white'); }; ``` -------------------------------- ### Load and Play Sound (Python) Source: https://github.com/q5js/q5.js/blob/main/lang/en/learn/sound.md Loads a sound file and plays it when the mouse is pressed. Sound volume can be adjusted. Note: This is a Python example for a q5.js context, implying a specific environment setup. ```python Canvas(200) sound = loadSound('/assets/jump.wav') sound.volume = 0.3 def mousePressed(): ssound.play() ``` -------------------------------- ### Basic Canvas Setup Source: https://github.com/q5js/q5.js/blob/main/_autodocs/README.md Initializes a 400x300 canvas and defines the setup and draw functions for basic drawing. The setup function sets the background to white, and the draw function draws a circle at the mouse position. ```javascript await Canvas(400, 300); // Define setup (runs once) q5.setup = function () { background('white'); }; // Define draw loop (runs ~60 times per second) q5.draw = function () { circle(mouseX, mouseY, 50); }; ``` -------------------------------- ### Respond to Mouse Release Event (webgpu) Source: https://github.com/q5js/q5.js/blob/main/lang/en/learn/input.md Define the `q5.mouseReleased` function to execute code when the mouse button is released. This example changes the background color and increments a gray value. Requires `await Canvas(200);` setup. ```javascript await Canvas(200); let gray = 0.4; q5.mouseReleased = function () { background(gray % 1); gray += 0.1; }; ``` -------------------------------- ### Draw circles based on touch/pointer input (WebGPU) Source: https://github.com/q5js/q5.js/blob/main/lang/en/learn/input.md Iterate through the `pointers` array in the `draw` function to get current touch and pointer coordinates. This example draws circles at each pointer's location. ```javascript q5.draw = function () { background(0.8); for (let pt of pointers) { circle(pt.x, pt.y, 100); } }; ``` -------------------------------- ### Load Addons with q5.js Source: https://github.com/q5js/q5.js/wiki/Addons To use addons, load them after q5.js. This example shows loading q5.js, setting up import maps for Box2D, and then loading q5play. ```html ``` -------------------------------- ### Start Recording Source: https://github.com/q5js/q5.js/blob/main/_autodocs/api-reference/dom-advanced.md Begins the audio/video recording process. You can specify a particular recorder instance or use the default one if available. ```javascript let rec = createRecorder(); record(rec); ``` -------------------------------- ### Respond to Mouse Press Event (webgpu) Source: https://github.com/q5js/q5.js/blob/main/lang/en/learn/input.md Define the `q5.mousePressed` function to execute code when the mouse button is pressed. This example changes the background color and increments a gray value. Requires `await Canvas(200);` setup. ```javascript await Canvas(200); let gray = 0.4; q5.mousePressed = function () { background(gray % 1); gray += 0.1; }; ``` -------------------------------- ### preload Source: https://github.com/q5js/q5.js/blob/main/_autodocs/api-reference/input-control.md Called before setup, used to load resources. The program waits for all preloads to complete. ```APIDOC ## preload ### Description Called before setup, used to load resources. The program waits for all preloads to complete. ### Method Function ### Parameters None ### Returns `void` ### Notes - Runs before setup - Use to load images, fonts, sounds with `load*` functions ### Example ```javascript let img; q5.preload = function () { img = loadImage('image.png'); }; ``` ``` -------------------------------- ### Load and Play Sound (WebGPU) Source: https://github.com/q5js/q5.js/blob/main/lang/en/learn/sound.md Loads a sound file and plays it on mouse press. Requires user interaction to start playback. Sound volume can be adjusted. ```javascript await Canvas(200); let sound = loadSound('/assets/jump.wav'); sound.volume = 0.3; q5.mousePressed = function () { sound.play(); }; ``` -------------------------------- ### Start defining a contour (hole) Source: https://github.com/q5js/q5.js/blob/main/_autodocs/api-reference/shapes.md Use `beginContour` to start defining a contour, which is used to create holes within a filled shape. This method is not available in q5 WebGPU. ```javascript beginContour(): void ``` -------------------------------- ### Respond to Mouse Move Event (webgpu) Source: https://github.com/q5js/q5.js/blob/main/lang/en/learn/input.md Define the `q5.mouseMoved` function to execute code when the mouse cursor moves. This example changes the background color and increments a gray value. Requires `await Canvas(200);` setup. ```javascript await Canvas(200); let gray = 0.4; q5.mouseMoved = function () { background(gray % 1); gray += 0.005; }; ``` -------------------------------- ### Respond to key press event (WebGPU) Source: https://github.com/q5js/q5.js/blob/main/lang/en/learn/input.md Define the `q5.keyPressed` function to execute code when a key is pressed. This example changes the background color. ```javascript await Canvas(200); let gray = 0.4; q5.keyPressed = function () { background(gray % 1); gray += 0.1; }; ``` -------------------------------- ### record Source: https://github.com/q5js/q5.js/blob/main/_autodocs/api-reference/dom-advanced.md Starts the recording process using a specified recorder. If no recorder is provided, it uses the default recorder. ```APIDOC ## record ### Description Starts recording. ### Method ```javascript record(recorder?: Recorder): void ``` ### Parameters #### Path Parameters - **recorder** (Recorder) - Optional - Recorder to use ### Returns `void` ### Example ```javascript let rec = createRecorder(); record(rec); ``` ``` -------------------------------- ### record Source: https://github.com/q5js/q5.js/blob/main/lang/en/learn/record.md Starts or resumes the canvas recording. ```APIDOC ## record Starts or resumes recording the canvas. ### Description Initiates the recording process. If no recorder has been created, one is automatically instantiated but not displayed. This method can also resume recording if it was previously paused. ``` -------------------------------- ### Get Image Subsection (Python) Source: https://github.com/q5js/q5.js/blob/main/lang/en/learn/image.md Extracts a subsection of an image using the get method and displays it. Requires an asynchronous Canvas setup and image loading. ```python Canvas(200) logo = await load('/q5js_logo.avif') cropped = logo.get(256, 256, 512, 512) image(cropped, -100, -100, 200, 200) ``` -------------------------------- ### Create Q5 WebGPU Instance with Python Syntax Source: https://github.com/q5js/q5.js/blob/main/lang/en/learn/advanced.md Initializes Q5 with the WebGPU renderer using Python syntax. The draw loop is set up to render a background and a circle that follows the mouse cursor. ```python q = await Q5.WebGPU('namespace') q.Canvas(200, 100) q.draw = () q.background(0.8) q.circle(q.mouseX, 0, 80) ``` -------------------------------- ### Get Image Subsection (WebGPU) Source: https://github.com/q5js/q5.js/blob/main/lang/en/learn/image.md Extracts a subsection of an image using the get method and displays it. Requires an asynchronous Canvas setup and image loading. ```javascript await Canvas(200); let logo = await load('/q5js_logo.avif'); let cropped = logo.get(256, 256, 512, 512); image(cropped, -100, -100, 200, 200); ``` -------------------------------- ### beginShape Source: https://github.com/q5js/q5.js/blob/main/_autodocs/api-reference/shapes.md Starts recording vertices for a custom shape. This function must be called before adding any vertices. ```APIDOC ## beginShape ### Description Starts recording vertices for a custom shape. ### Method `beginShape(): void` ### Returns `void` ### Example ```javascript await Canvas(200); strokeWeight(2); beginShape(); vertex(-80, -80); vertex(40, -60); vertex(80, 60); vertex(-60, 80); endShape(true); ``` ``` -------------------------------- ### Get Image Subsection (Canvas 2D) Source: https://github.com/q5js/q5.js/blob/main/lang/en/learn/image.md Extracts a subsection of an image using the get method and displays it within a setup function. Requires loadImage for asynchronous loading. ```javascript createCanvas(200); let logo = loadImage('/q5js_logo.avif'); function setup() { let cropped = logo.get(256, 256, 512, 512); image(cropped, 0, 0, 200, 200); } ``` -------------------------------- ### WebGPU with Fallback Initialization Source: https://github.com/q5js/q5.js/blob/main/_autodocs/configuration.md Create a Q5 instance that attempts to use the WebGPU renderer but automatically falls back to Canvas 2D if WebGPU is not available in the browser. ```javascript let q5Instance = new Q5(scope, parent, 'webgpu-fallback'); ``` -------------------------------- ### Initialize Canvas and Draw Circle in q5.js Source: https://github.com/q5js/q5.js/blob/main/README.md This snippet demonstrates the basic setup for q5.js, initializing a canvas of a specified size and drawing a circle. Ensure the Canvas function is awaited for proper initialization. ```javascript await Canvas(200); circle(0, 0, 80); ``` -------------------------------- ### Draw a capsule with fixed coordinates (c2d) Source: https://github.com/q5js/q5.js/blob/main/lang/en/learn/shapes.md Draws a capsule using specified start and end points and a radius. This example is for the c2d backend. ```javascript createCanvas(200, 100); background(200); strokeWeight(5); capsule(40, 40, 160, 60, 10); ``` -------------------------------- ### Complete Example with Drawing Source: https://github.com/q5js/q5.js/blob/main/_autodocs/README.md Sets up a 200x200 canvas with a light blue background. The draw function fills circles with red, draws a blue line, and configures stroke weight. ```javascript await Canvas(200, 200); q5.setup = function () { background('lightblue'); }; q5.draw = function () { fill('red'); circle(mouseX, mouseY, 30); stroke('blue'); strokeWeight(2); line(-100, -100, 100, 100); }; ``` -------------------------------- ### Save Recording (webgpu) Source: https://github.com/q5js/q5.js/blob/main/lang/en/learn/record.md Saves the current recording with a specified file name for webgpu. Recording is started if not already in progress. ```javascript q5.draw = function () { square(mouseX, jit(100), 10); }; q5.mousePressed = function () { if (!recording) record(); else saveRecording('squares'); }; ``` -------------------------------- ### Draw a capsule with fixed coordinates (Python) Source: https://github.com/q5js/q5.js/blob/main/lang/en/learn/shapes.md Draws a capsule using specified start and end points and a radius. This example is for the python backend. ```python Canvas(200, 100) background(0.8) strokeWeight(5) capsule(-60, -10, 60, 10, 10) ``` -------------------------------- ### Display Text (webgpu) Source: https://github.com/q5js/q5.js/blob/main/lang/en/learn/text.md Renders 'Hello, world!' with a silver background using the webgpu renderer. Adjusts text size and position. ```js await Canvas(200, 100); background('silver'); textSize(32); text('Hello, world!', -88, 10); ``` -------------------------------- ### Get Text Ascent in WebGPU Source: https://github.com/q5js/q5.js/blob/main/lang/en/learn/text.md Example of using textAscent to determine the ascent of text in a WebGPU canvas. Text size is controlled by the mouse X position. ```js q5.draw = function () { background(0.8); textSize(abs(mouseX)); rect(-90, 90, textWidth('A'), -textAscent()); text('A', -90, 90); }; ``` -------------------------------- ### Create Q5 WebGPU Instance with Namespace Scope Source: https://github.com/q5js/q5.js/blob/main/lang/en/learn/advanced.md Initialize Q5 using the WebGPU renderer in 'namespace' mode. This allows for advanced graphics capabilities without global scope pollution. The draw function is defined to create dynamic visuals. ```javascript let q = await Q5.WebGPU('namespace'); q.Canvas(200, 100); q.draw = () => { q.background(0.8); q.circle(q.mouseX, 0, 80); }; ``` -------------------------------- ### Resize Image (Canvas 2D) Source: https://github.com/q5js/q5.js/blob/main/lang/en/learn/image.md Resizes an image to the specified width and height before drawing it. This example uses the Canvas 2D rendering context and requires a setup function. ```javascript createCanvas(200); let logo = loadImage('/q5js_logo.avif'); function setup() { logo.resize(128, 128); image(logo, 0, 0, 200, 200); } ``` -------------------------------- ### update Source: https://github.com/q5js/q5.js/blob/main/_autodocs/api-reference/input-control.md Called once per frame, after setup. An optional alternative to draw, useful for game logic separate from rendering. ```APIDOC ## update ### Description Called once per frame, after setup. An optional alternative to draw, useful for game logic separate from rendering. ### Method Function ### Parameters None ### Returns `void` ### Notes - Optional alternative to draw - Runs before rendering ### Example ```javascript q5.update = function () { // Game logic here }; ``` ``` -------------------------------- ### Display elapsed time using millis Source: https://github.com/q5js/q5.js/blob/main/_autodocs/api-reference/input-control.md Get the total time in milliseconds since the program started using the millis() function. This is useful for timing events or tracking program duration. ```javascript let elapsed = millis(); text(`Elapsed: ${elapsed}ms`, 10, 10); ``` -------------------------------- ### Q5.WebGPU Source: https://github.com/q5js/q5.js/blob/main/lang/en/learn/advanced.md Creates a new Q5 instance utilizing the WebGPU renderer for advanced graphics capabilities. ```APIDOC ## Q5.WebGPU Creates a new Q5 instance that uses [q5's WebGPU renderer](https://github.com/q5js/q5.js/wiki/q5-WebGPU-renderer). ### webgpu ```js let q = await Q5.WebGPU('namespace'); q.Canvas(200, 100); q.draw = () => { q.background(0.8); q.circle(q.mouseX, 0, 80); }; ``` ### python ```py q = await Q5.WebGPU('namespace') q.Canvas(200, 100) q.draw = () => q.background(0.8) q.circle(q.mouseX, 0, 80) ``` ``` -------------------------------- ### Respond to key release event (WebGPU) Source: https://github.com/q5js/q5.js/blob/main/lang/en/learn/input.md Use the `q5.keyReleased` function to trigger actions when a key is released. This example adjusts the background color based on a `gray` variable. ```javascript await Canvas(200); let gray = 0.4; q5.keyReleased = function () { background(gray % 1); gray += 0.1; }; ``` -------------------------------- ### Respond to Mouse Move Event (c2d) Source: https://github.com/q5js/q5.js/blob/main/lang/en/learn/input.md Define the `mouseMoved` function to execute code when the mouse cursor moves. This example changes the background color and increments a gray value. Requires `createCanvas(200)` setup. ```javascript createCanvas(200); let gray = 95; function mouseMoved() { background(gray % 256); gray++; } ``` -------------------------------- ### Display Q5 Version with WebGPU Renderer Source: https://github.com/q5js/q5.js/blob/main/lang/en/learn/advanced.md Access the current minor version of Q5.js and display it on the canvas. This example uses the WebGPU renderer and assumes a background and text styling are already set. ```javascript await Canvas(200); background(0.8); textSize(64); textAlign(CENTER, CENTER); text('v' + Q5.version, 0, 0); ``` -------------------------------- ### Respond to Mouse Move Event (python) Source: https://github.com/q5js/q5.js/blob/main/lang/en/learn/input.md Define the `mouseMoved` function to execute code when the mouse cursor moves. This example changes the background color and increments a gray value. Requires `Canvas(200)` setup. ```python Canvas(200) gray = 0.4 def mouseMoved(): background(gray % 1) gray += 0.005 ``` -------------------------------- ### Respond to Mouse Release Event (c2d) Source: https://github.com/q5js/q5.js/blob/main/lang/en/learn/input.md Define the `mouseReleased` function to execute code when the mouse button is released. This example changes the background color and increments a gray value. Requires `createCanvas(200)` setup. ```javascript createCanvas(200); let gray = 95; function mouseReleased() { background(gray % 256); gray += 40; } ``` -------------------------------- ### JavaScript Touch Event Handler for Touch Start Source: https://github.com/q5js/q5.js/blob/main/_autodocs/api-reference/input-control.md This snippet draws a circle at the location of the first touch point when a touch begins. It should be assigned to the q5.touchStarted function. ```javascript q5.touchStarted = function () { circle(touches[0].x, touches[0].y, 50); }; ``` -------------------------------- ### userStartAudio Source: https://github.com/q5js/q5.js/blob/main/_autodocs/configuration.md Initializes the audio system, which is often required by modern browsers due to autoplay policies. This function should be called in response to a user interaction. ```APIDOC ## userStartAudio ### Description Initialize audio (required by some browsers). ### Method POST (conceptual) ### Endpoint N/A (Function call) ### Parameters None ### Notes - Some browsers require user interaction to play audio. - Call in response to user event (click, touch, etc.). ### Request Example ```javascript userStartAudio(); ``` ### Response None ``` -------------------------------- ### Respond to Mouse Release Event (python) Source: https://github.com/q5js/q5.js/blob/main/lang/en/learn/input.md Define the `mouseReleased` function to execute code when the mouse button is released. This example changes the background color and increments a gray value. Requires `Canvas(200)` setup. ```python Canvas(200) gray = 0.4 def mouseReleased(): background(gray % 1) gray += 0.1 ``` -------------------------------- ### Ceiling function in q5.js (webgpu) Source: https://github.com/q5js/q5.js/blob/main/lang/en/learn/math.md Rounds a number up using the ceil function in a webgpu context. Requires Canvas setup. ```javascript await Canvas(200, 100); background(0.8); textSize(32); text(ceil(PI), -90, 10); ``` -------------------------------- ### Respond to Mouse Press Event (c2d) Source: https://github.com/q5js/q5.js/blob/main/lang/en/learn/input.md Define the `mousePressed` function to execute code when the mouse button is pressed. This example changes the background color and increments a gray value. Requires `createCanvas(200)` setup. ```javascript createCanvas(200); let gray = 95; function mousePressed() { background(gray % 256); gray += 40; } ``` -------------------------------- ### Display Text (python) Source: https://github.com/q5js/q5.js/blob/main/lang/en/learn/text.md Renders 'Hello, world!' with a silver background using the python renderer. Sets text size and position. ```py Canvas(200, 100) background('silver') textSize(32) text('Hello, world!', -88, 10) ``` -------------------------------- ### Resize Image (WebGPU) Source: https://github.com/q5js/q5.js/blob/main/lang/en/learn/image.md Resizes an image to the specified width and height before drawing it. This example uses the WebGPU rendering context. ```javascript await Canvas(200); let logo = await load('/q5js_logo.avif'); logo.resize(128, 128); image(logo, -100, -100, 200, 200); ``` -------------------------------- ### Handle Touch Start Event (webgpu) Source: https://github.com/q5js/q5.js/blob/main/lang/en/learn/input.md Define the touchStarted function to respond to touch down events when using the webgpu backend. Return true to enable default touch gestures. ```javascript await Canvas(200); let gray = 0.4; q5.touchStarted = function () { background(gray % 1); gray += 0.1; }; ``` -------------------------------- ### Respond to Mouse Press Event (python) Source: https://github.com/q5js/q5.js/blob/main/lang/en/learn/input.md Define the `mousePressed` function to execute code when the mouse button is pressed. This example changes the background color and increments a gray value. Requires `Canvas(200)` setup. ```python Canvas(200) gray = 0.4 def mousePressed(): background(gray % 1) gray += 0.1 ``` -------------------------------- ### Display Q5 Version with Python Syntax Source: https://github.com/q5js/q5.js/blob/main/lang/en/learn/advanced.md Demonstrates how to display the Q5.js version using Python-like syntax, suitable for environments that support this translation. ```python Canvas(200) background(0.8) textSize(64) textAlign(CENTER, CENTER) text('v' + Q5.version, 0, 0) ``` -------------------------------- ### Load Assets with Preload Source: https://github.com/q5js/q5.js/blob/main/_autodocs/api-reference/input-control.md Use the preload function to load external assets like images before the program starts. The program will wait for all loading to complete. ```javascript let img; q5.preload = function () { img = loadImage('image.png'); }; ``` -------------------------------- ### Create Recorder (webgpu) Source: https://github.com/q5js/q5.js/blob/main/lang/en/learn/record.md Creates a recorder instance for webgpu. The bitrate can be programmatically set. Audio is captured by default. ```javascript await Canvas(200); let rec = createRecorder(); rec.bitrate = 10; q5.draw = function () { circle(mouseX, jit(halfHeight), 10); }; ``` -------------------------------- ### Run Unit Tests with Jest (Node.js) Source: https://github.com/q5js/q5.js/blob/main/test/readme.md Execute unit tests using Jest in a Node.js environment. Ensure Jest is installed globally. ```zsh jest ``` -------------------------------- ### Inset Image Region (WebGPU) Source: https://github.com/q5js/q5.js/blob/main/lang/en/learn/image.md Uses the inset method to copy a region of an image and display it. Requires an asynchronous Canvas setup and image loading. ```javascript await Canvas(200); let logo = await load('/q5js_logo.avif'); logo.inset(256, 256, 512, 512, 0, 0, 256, 256); image(logo, -100, -100, 200, 200); ``` -------------------------------- ### Enable Smooth Rendering (Canvas 2D) Source: https://github.com/q5js/q5.js/blob/main/lang/en/learn/image.md Enables smooth rendering for images displayed larger than their original size. This is the default behavior, so this function is only effective if `noSmooth()` has been previously called. This example uses the Canvas 2D rendering context and requires a setup function. ```javascript createCanvas(200); let icon = loadImage('/q5js_icon.png'); function setup() { image(icon, 0, 0, 200, 200); } ``` -------------------------------- ### Basic Instance Mode with Namespace Source: https://github.com/q5js/q5.js/wiki/Instance-Mode Instantiates a q5 sketch with a custom namespace. All q5 functions and variables are accessed via the namespace object. ```javascript let q = new Q5('namespace'); q.createCanvas(400); q.draw = () => { q.background(100); }; ``` -------------------------------- ### get Source: https://github.com/q5js/q5.js/blob/main/_autodocs/api-reference/images-text.md Gets pixel color or a region of the canvas. Automatically calls loadPixels() if needed. ```APIDOC ## get ### Description Gets pixel color or a region of the canvas. ### Method get ### Parameters #### Path Parameters - **x** (number) - Required - x-coordinate - **y** (number) - Required - y-coordinate - **w** (number) - Optional - Width of region - **h** (number) - Optional - Height of region ### Returns `Q5.Image | number[]` - Pixel color or image region ### Notes - If no width/height, returns color at that pixel - Automatically calls `loadPixels()` if needed ### Example ```javascript // Get color at a point let c = get(10, 10); // Get a region as an image let region = get(0, 0, 50, 50); ``` ``` -------------------------------- ### Example: Rounding PI in WebGPU Source: https://github.com/q5js/q5.js/blob/main/lang/en/learn/math.md Demonstrates using the `round` function with `PI` in a WebGPU context. Sets up a canvas, background, text size, and displays the rounded value. ```javascript await Canvas(200, 100); background(0.8); textSize(32); text(round(PI, 5), -90, 10); ``` -------------------------------- ### Create and Control a Video Element (WebGPU) Source: https://github.com/q5js/q5.js/blob/main/lang/en/learn/dom.md Creates a video element, sets its properties for autoplay, and displays it on the canvas. Videos must be muted to autoplay. ```javascript await Canvas(1); let vid = createVideo('/assets/apollo4.mp4'); vid.size(200, 150); vid.autoplay = vid.muted = vid.loop = true; vid.controls = true; ``` -------------------------------- ### Drawing State Management in q5.js Source: https://github.com/q5js/q5.js/blob/main/_autodocs/README.md This example demonstrates how to manage drawing styles in q5.js using `pushStyles()` and `popStyles()`. It draws two circles with different fill colors without affecting subsequent drawing operations. ```javascript q5.draw = function () { pushStyles(); fill('red'); circle(-50, 0, 30); popStyles(); fill('blue'); circle(50, 0, 30); }; ``` -------------------------------- ### Get Color Components with Color.levels Source: https://github.com/q5js/q5.js/blob/main/_autodocs/api-reference/color-and-style.md Access the `levels` property of a Color object to get an array of its RGBA components, scaled to the range of 0-255. ```javascript let c = color('red'); console.log(c.levels); // [255, 0, 0, 255] ``` -------------------------------- ### Clone q5.js Repository Source: https://github.com/q5js/q5.js/wiki/Contributor-Guide Use the `git clone` command to download the q5.js repository to your local machine. ```sh git clone https://github.com/q5js/q5.js.git ``` -------------------------------- ### Get Actual Frame Rate - JavaScript Source: https://github.com/q5js/q5.js/blob/main/_autodocs/api-reference/input-control.md Use getFPS() to get the current, actual frame rate being achieved by the sketch. This reflects the real-time performance. ```javascript q5.draw = function () { let fps = getFPS(); text(`FPS: ${fps}`, 10, 10); }; ``` -------------------------------- ### q5.js File Structure Source: https://github.com/q5js/q5.js/blob/main/_autodocs/MANIFEST.md Illustrates the directory layout for the generated q5.js documentation, including the index, types, configuration, and API reference files. ```bash output/ ├── README.md # Index and quick reference guide ├── types.md # Complete type definitions and constants ├── configuration.md # Canvas options and global configuration └── api-reference/ ├── canvas.md # Canvas creation and management ├── shapes.md # 2D shape drawing functions ├── color-and-style.md # Color, fill, stroke, and visual styling ├── vector-math.md # Vector operations and math functions ├── images-text.md # Image loading/manipulation and text rendering ├── input-control.md # User input and program control flow ├── transforms-random.md # 2D transformations and random numbers └── dom-advanced.md # DOM manipulation and advanced features ``` -------------------------------- ### Get Pixel Color (Canvas 2D) Source: https://github.com/q5js/q5.js/blob/main/lang/en/learn/image.md Retrieves the color of a pixel at the mouse coordinates. Requires loadPixels() to be called before get() for updated pixel data. Not applicable to WebGPU. ```javascript function draw() { background(200); noStroke(); circle(100, 100, frameCount % 200); loadPixels(); let col = get(mouseX, mouseY); text(col, mouseX, mouseY); } ``` -------------------------------- ### userStartAudio Source: https://github.com/q5js/q5.js/blob/main/lang/en/learn/sound.md Creates a new AudioContext or resumes it if it was suspended. Returns a promise that resolves when the AudioContext is resumed. ```APIDOC ## userStartAudio Creates a new AudioContext or resumes it if it was suspended. ``` @returns {Promise} a promise that resolves when the AudioContext is resumed ``` ``` -------------------------------- ### Set and Get Frame Rate - JavaScript Source: https://github.com/q5js/q5.js/blob/main/_autodocs/api-reference/input-control.md Use frameRate() to set the target frame rate for the sketch. Call it without arguments to get the current frame rate. ```javascript frameRate(30); // Slow down to 30 FPS let rate = frameRate(); console.log(rate); ``` -------------------------------- ### Display Text (c2d) Source: https://github.com/q5js/q5.js/blob/main/lang/en/learn/text.md Renders 'Hello, world!' with a silver background using the c2d renderer. Sets text size and position. ```js createCanvas(200, 100); background('silver'); textSize(32); text('Hello, world!', 12, 60); ``` -------------------------------- ### Get Current FPS (Python) Source: https://github.com/q5js/q5.js/blob/main/lang/en/learn/display.md Gets the current frames per second (FPS) in a Python environment, which can exceed the target frame rate. Includes setting frame rate to 1 for testing. ```python def draw(): background(0.8) frameRate(1) textSize(64) text(getFPS(), -92, 20) ``` -------------------------------- ### Navigate to Desktop Folder Source: https://github.com/q5js/q5.js/wiki/Contributor-Guide Use the `cd` command in your terminal to navigate to the desired project folder, such as your Desktop. ```sh cd ~/Desktop ``` -------------------------------- ### Get Current FPS (webGPU) Source: https://github.com/q5js/q5.js/blob/main/lang/en/learn/display.md Gets the current frames per second (FPS) in the webGPU environment, which can exceed the target frame rate. Includes setting frame rate to 1 for testing. ```javascript q5.draw = function () { background(0.8); frameRate(1); textSize(64); text(getFPS(), -92, 20); }; ``` -------------------------------- ### Create Recorder (python) Source: https://github.com/q5js/q5.js/blob/main/lang/en/learn/record.md Creates a recorder instance for Python. The bitrate can be programmatically set. Audio is captured by default. ```python Canvas(200) rec = createRecorder() rec.bitrate = 10 def draw(): circle(mouseX, jit(halfHeight), 10) ``` -------------------------------- ### Get Current FPS (Canvas 2D) Source: https://github.com/q5js/q5.js/blob/main/lang/en/learn/display.md Gets the current frames per second (FPS) in the Canvas 2D environment, which can exceed the target frame rate. Includes setting frame rate to 1 for testing. ```javascript function draw() { background(200); frameRate(1); textSize(64); text(getFPS(), 8, 120); } ``` -------------------------------- ### Example: Rounding PI in Python Source: https://github.com/q5js/q5.js/blob/main/lang/en/learn/math.md Demonstrates using the `round` function with `PI` in a Python context. Sets up a canvas, background, text size, and displays the rounded value. ```python Canvas(200, 100) background(0.8) textSize(32) text(round(PI, 5), -90, 10) ``` -------------------------------- ### getTargetFrameRate Source: https://github.com/q5js/q5.js/blob/main/_autodocs/api-reference/input-control.md Gets the target frame rate that was set for the drawing loop. ```APIDOC ## getTargetFrameRate ### Description Gets the target frame rate. ### Method INVOKE ### Endpoint getTargetFrameRate(): number ### Returns `number` - Target frame rate in Hz (0 if not set) ### Request Example ```javascript let target = getTargetFrameRate(); console.log(`Target: ${target} FPS`); ``` ``` -------------------------------- ### Transformation Example in q5.js Source: https://github.com/q5js/q5.js/blob/main/_autodocs/README.md This snippet illustrates the use of transformation matrices in q5.js for drawing. It applies translation and rotation to a rectangle, demonstrating how to manage drawing states with `push()` and `pop()`. ```javascript q5.draw = function () { background('white'); push(); translate(100, 100); rotate(frameCount * 0.05); rect(0, 0, 50, 50); pop(); }; ``` -------------------------------- ### randomGenerator() Source: https://github.com/q5js/q5.js/blob/main/_autodocs/api-reference/transforms-random.md Gets or creates a custom random number generator function. ```APIDOC ## randomGenerator Gets or creates a custom random number generator. ### Signature ```javascript randomGenerator(fn?: () => number): () => number ``` ### Parameters #### Path Parameters - **fn** (function) - Optional - Custom random function ### Returns - **() => number** - Random generator function ### Example ```javascript let customRandom = randomGenerator(() => Math.random()); ``` ``` -------------------------------- ### Initialize WebGPU Renderer Source: https://github.com/q5js/q5.js/blob/main/_autodocs/README.md Initializes the q5.js canvas with the WebGPU renderer for high-performance, GPU-accelerated graphics. Ensure your browser supports WebGPU. ```javascript await Canvas(400, 300, 'webgpu'); ``` -------------------------------- ### loop Source: https://github.com/q5js/q5.js/blob/main/_autodocs/api-reference/input-control.md Starts the draw loop. The draw loop is enabled by default. ```APIDOC ## loop ### Description Starts the draw loop. The draw loop is enabled by default. ### Method INVOKE ### Endpoint loop(): void ### Returns `void` ### Request Example ```javascript noLoop(); // Stop drawing // Later... loop(); // Resume drawing ``` ``` -------------------------------- ### Create and Style a Div Element (webgpu) Source: https://github.com/q5js/q5.js/blob/main/lang/en/learn/dom.md Creates a new div element, positions and sizes it, and applies various styles for display. This example is for the webgpu rendering context. ```javascript await Canvas(200); let el = createEl('div', '*'); el.position(50, 50); el.size(100, 100); el.style.fontSize = '136px'; el.style.textAlign = 'center'; el.style.backgroundColor = 'blue'; el.style.color = 'white'; ``` -------------------------------- ### Canvas Initialization Function Source: https://github.com/q5js/q5.js/blob/main/_autodocs/README.md The entry point function to initialize q5.js and create the drawing surface. It accepts optional width, height, and options parameters. ```javascript Canvas(width?: number, height?: number, options?: object): Promise ``` -------------------------------- ### getFPS Source: https://github.com/q5js/q5.js/blob/main/_autodocs/api-reference/input-control.md Gets the actual frame rate that the drawing loop is currently achieving. ```APIDOC ## getFPS ### Description Gets the actual frame rate. ### Method INVOKE ### Endpoint getFPS(): number ### Returns `number` - Actual frame rate achieved ### Request Example ```javascript q5.draw = function () { let fps = getFPS(); text(`FPS: ${fps}`, 10, 10); }; ``` ``` -------------------------------- ### Add Lifecycle Hook to q5.js Source: https://github.com/q5js/q5.js/wiki/Addons This example demonstrates adding a 'predraw' lifecycle hook to q5.js that sets the background to pink before the user's draw function executes. ```javascript /* addon.js */ Q5.addHook('predraw', function () { const $ = this; $.background('pink'); }); /* sketch.js */ function draw() { circle(mouseX, mouseY, 50); } ``` -------------------------------- ### Get Canvas Height (python) Source: https://github.com/q5js/q5.js/blob/main/lang/en/learn/display.md Accesses the canvas height property in a Python context. ```python Canvas(200, 80) circle(0, 0, height) ``` -------------------------------- ### Apply Tint Overlay (webgpu) Source: https://github.com/q5js/q5.js/blob/main/lang/en/learn/image.md Apply a tint color overlay to images using `tint(r, g, b, alpha)`. The alpha value controls tint strength. Tinting affects subsequent images and is cached for performance. ```javascript await Canvas(200); let logo = await load('/q5js_logo.avif'); tint(1, 0, 0, 0.5); image(logo, -100, -100, 200, 200); ``` -------------------------------- ### Get Canvas Width (python) Source: https://github.com/q5js/q5.js/blob/main/lang/en/learn/display.md Accesses the canvas width property in a Python context. ```python Canvas(200, 120) circle(0, 0, width) ``` -------------------------------- ### Load Multiple Audio Files in WebGPU Source: https://github.com/q5js/q5.js/blob/main/lang/en/learn/utilities.md Loads two audio files and plays them based on mouse clicks. Left-click plays the first, right-click plays the second. ```javascript await Canvas(200); let [jump, retro] = await load('/assets/jump.wav', '/assets/retro.flac'); q5.mousePressed = function () { if (mouseButton == 'left') jump.play(); if (mouseButton == 'right') retro.play(); }; // ``` -------------------------------- ### beginContour Source: https://github.com/q5js/q5.js/blob/main/_autodocs/api-reference/shapes.md Starts recording vertices for a contour, which can be used to create holes within a shape. ```APIDOC ## beginContour ### Description Starts recording vertices for a contour (hole in a shape). ### Method `beginContour(): void` ### Returns `void` ### Notes - Not available in q5 WebGPU - Used to create holes in filled shapes ``` -------------------------------- ### Run Unit Tests with Deno Source: https://github.com/q5js/q5.js/blob/main/test/readme.md Execute unit tests using Deno. This command requires unstable Node.js globals and all permissions. Ensure Deno is installed and the project is in the current directory. ```zsh deno test --unstable-node-globals -A ``` -------------------------------- ### Restart the draw loop (c2d) Source: https://github.com/q5js/q5.js/blob/main/lang/en/learn/display.md Starts the draw loop again if it was previously stopped with noLoop(). ```javascript createCanvas(200); noLoop(); function draw() { circle(frameCount * 5, 100, 80); } function mousePressed() { loop(); } ``` -------------------------------- ### Create Input Element in q5.js Source: https://github.com/q5js/q5.js/blob/main/lang/en/learn/dom.md Creates an input element. Use the `value` and `placeholder` properties to set its content. An event listener can be added to react to input changes. Supports webgpu, python, and c2d. ```javascript await Canvas(200, 100); textSize(64); let input = createInput(); input.placeholder = 'Type here!'; input.size(200, 32); input.addEventListener('input', () => { background('orange'); text(input.value, -90, 30); }); ``` ```python Canvas(200, 100) textSize(64) input = createInput() input.placeholder = 'Type here!' input.size(200, 32) input.addEventListener('input', () => background('orange') text(input.value, -90, 30) }) ``` ```javascript createCanvas(200, 100); textSize(64); let input = createInput(); input.placeholder = 'Type here!'; input.size(200, 32); input.addEventListener('input', () => { background('orange'); text(input.value, 10, 70); }); ``` -------------------------------- ### Restart the draw loop (python) Source: https://github.com/q5js/q5.js/blob/main/lang/en/learn/display.md Starts the draw loop again if it was previously stopped with noLoop(). ```python Canvas(200) noLoop() def draw(): circle(frameCount * 5 - 100, 0, 80) def mousePressed(): loop() ``` -------------------------------- ### Import Full q5.js Module Source: https://github.com/q5js/q5.js/wiki/Modular-Use Import the entire q5.js library as a JavaScript module. 'Q5' and 'createCanvas' are added to the global scope. ```javascript import 'https://q5js.org/q5.js'; ``` -------------------------------- ### Restart the draw loop (webgpu) Source: https://github.com/q5js/q5.js/blob/main/lang/en/learn/display.md Starts the draw loop again if it was previously stopped with noLoop(). ```javascript await Canvas(200); noLoop(); q5.draw = function () { circle(frameCount * 5 - 100, 0, 80); }; q5.mousePressed = function () { loop(); }; ``` -------------------------------- ### Create and Style a Div Element (python) Source: https://github.com/q5js/q5.js/blob/main/lang/en/learn/dom.md Creates a new div element, positions and sizes it, and applies various styles for display. This example is for the python rendering context. ```python Canvas(200) el = createEl('div', '*') el.position(50, 50) el.size(100, 100) el.style.fontSize = '136px' el.style.textAlign = 'center' el.style.backgroundColor = 'blue' el.style.color = 'white' ``` -------------------------------- ### Get Half Canvas Height (python) Source: https://github.com/q5js/q5.js/blob/main/lang/en/learn/display.md Accesses half the canvas height in a Python context. ```python Canvas(200, 80) circle(0, 0, halfHeight) ``` -------------------------------- ### Get Half Canvas Width (python) Source: https://github.com/q5js/q5.js/blob/main/lang/en/learn/display.md Accesses half the canvas width in a Python context. ```python Canvas(200, 80) circle(0, 0, halfWidth) ``` -------------------------------- ### Handle Touch Start Event (python) Source: https://github.com/q5js/q5.js/blob/main/lang/en/learn/input.md Define the touchStarted function to respond to touch down events when using the python backend. Return true to enable default touch gestures. ```python Canvas(200) gray = 0.4 def touchStarted(): background(gray % 1) gray += 0.1 ``` -------------------------------- ### Get Current Second Source: https://github.com/q5js/q5.js/blob/main/_autodocs/api-reference/input-control.md Retrieves the current second (0-59) as a number. Useful for timing and animation. ```javascript let s = second(); ``` -------------------------------- ### createGraphics Source: https://github.com/q5js/q5.js/blob/main/lang/en/learn/image.md Creates a graphics buffer with the specified width, height, and optional configurations. Graphics looping is disabled by default in q5 WebGPU. ```APIDOC ## createGraphics Creates a graphics buffer. Graphics looping is disabled by default in q5 WebGPU. See issue [#104](https://github.com/q5js/q5.js/issues/104) for details. @param {number} w width @param {number} h height @param {object} [opt] options @returns {Q5} a new Q5 graphics buffer ``` -------------------------------- ### Get Current Minute Source: https://github.com/q5js/q5.js/blob/main/_autodocs/api-reference/input-control.md Retrieves the current minute (0-59) as a number. Useful for time-based calculations. ```javascript let m = minute(); ``` -------------------------------- ### Set Text Size Dynamically (webgpu) Source: https://github.com/q5js/q5.js/blob/main/lang/en/learn/text.md Sets the text size based on the absolute mouse X position within the draw loop for the webgpu context. Requires q5.draw to be defined. ```javascript q5.draw = function () { background(0.8); textSize(abs(mouseX)); text('A', -90, 90); }; ``` -------------------------------- ### Get Current Hour Source: https://github.com/q5js/q5.js/blob/main/_autodocs/api-reference/input-control.md Retrieves the current hour (0-23) as a number. Useful for time-based logic. ```javascript let h = hour(); ``` -------------------------------- ### Import All q5.js Core Modules Source: https://github.com/q5js/q5.js/wiki/Modular-Use Import all core modules that are included in the default 'q5.js' bundle. This allows for granular control over which parts of the library are loaded. ```javascript import 'https://q5js.org/src/q5-core.js'; import 'https://q5js.org/src/q5-canvas.js'; import 'https://q5js.org/src/q5-c2d-canvas.js'; import 'https://q5js.org/src/q5-c2d-shapes.js'; import 'https://q5js.org/src/q5-c2d-image.js'; import 'https://q5js.org/src/q5-c2d-soft-filters.js'; import 'https://q5js.org/src/q5-c2d-text.js'; import 'https://q5js.org/src/q5-color.js'; import 'https://q5js.org/src/q5-display.js'; import 'https://q5js.org/src/q5-dom.js'; import 'https://q5js.org/src/q5-fes.js'; import 'https://q5js.org/src/q5-input.js'; import 'https://q5js.org/src/q5-lang.js'; import 'https://q5js.org/src/q5-math.js'; import 'https://q5js.org/src/q5-record.js'; import 'https://q5js.org/src/q5-sound.js'; import 'https://q5js.org/src/q5-util.js'; import 'https://q5js.org/src/q5-vector.js'; import 'https://q5js.org/src/q5-webgpu.js'; ``` -------------------------------- ### Get Current Year Source: https://github.com/q5js/q5.js/blob/main/_autodocs/api-reference/input-control.md Retrieves the current year as a number. Useful for date-based logic or logging. ```javascript let y = year(); console.log(`Year: ${y}`); ``` -------------------------------- ### Create Graphics-Scoped Q5 Instance Source: https://github.com/q5js/q5.js/blob/main/_autodocs/configuration.md Create an off-screen graphics buffer for compositing. Requires parent and renderer arguments. ```javascript let g = new Q5('graphics', parent, renderer); ``` -------------------------------- ### Apply Tint Overlay (python) Source: https://github.com/q5js/q5.js/blob/main/lang/en/learn/image.md Apply a tint color overlay to images using `tint(r, g, b, alpha)`. The alpha value controls tint strength. Tinting affects subsequent images and is cached for performance. ```python Canvas(200) logo = await load('/q5js_logo.avif') tint(1, 0, 0, 0.5) image(logo, -100, -100, 200, 200) ``` -------------------------------- ### Draw Bezier Curve Source: https://github.com/q5js/q5.js/blob/main/_autodocs/api-reference/shapes.md Draws a Bezier curve. Requires canvas setup and background color. ```javascript await Canvas(200); background(0.8); bezier(-80, -80, -80, 80, 80, -80, 80, 80); ``` -------------------------------- ### Create and Control a Video Element (Python) Source: https://github.com/q5js/q5.js/blob/main/lang/en/learn/dom.md Creates a video element in Python, setting properties for autoplay and controls. Videos must be muted to autoplay. ```python Canvas(1) vid = createVideo('/assets/apollo4.mp4') vid.size(200, 150) vid.autoplay = vid.muted = vid.loop = True vid.controls = True ``` -------------------------------- ### Get Absolute Value with abs() Source: https://github.com/q5js/q5.js/blob/main/_autodocs/api-reference/vector-math.md Returns the absolute value of a number. Use this when you need a non-negative magnitude. ```javascript console.log(abs(-5)); // 5 ``` -------------------------------- ### Create Image Element in q5.js Source: https://github.com/q5js/q5.js/blob/main/lang/en/learn/dom.md Creates an image element from a given source URL. Allows for positioning and sizing. Compatible with webgpu, python, and c2d. ```javascript await Canvas(200, 100); let img = createImg('/assets/q5play_logo.avif'); img.position(0, 0).size(100, 100); ``` ```python Canvas(200, 100) img = createImg('/assets/q5play_logo.avif') img.position(0, 0).size(100, 100) ``` ```javascript createCanvas(200, 100); let img = createImg('/assets/q5play_logo.avif'); img.position(0, 0).size(100, 100); ``` -------------------------------- ### Create a Recorder Instance Source: https://github.com/q5js/q5.js/blob/main/_autodocs/api-reference/dom-advanced.md Initializes a new recorder object. This is the first step before any recording operations can be performed. ```javascript let recorder = createRecorder(); ``` -------------------------------- ### Get 2D Vector Heading Source: https://github.com/q5js/q5.js/blob/main/_autodocs/api-reference/vector-math.md Calculates the angle of a 2D vector in radians. This indicates the direction the vector is pointing. ```javascript let v = createVector(1, 0); console.log(v.heading()); // 0 (pointing right) ``` -------------------------------- ### Convert Color to String with Color.toString Source: https://github.com/q5js/q5.js/blob/main/_autodocs/api-reference/color-and-style.md Use the `toString()` method to get a CSS-compatible string representation of a Color object. ```javascript let c = color('red'); console.log(c.toString()); // "rgba(255, 0, 0, 1)" ``` -------------------------------- ### Create Image with q5.js Source: https://github.com/q5js/q5.js/blob/main/_autodocs/api-reference/images-text.md Creates a new blank image with the specified width and height. This new image can then be drawn upon. ```javascript let img = createImage(200, 200); // Draw on the image ``` -------------------------------- ### Get Current Day of Month Source: https://github.com/q5js/q5.js/blob/main/_autodocs/api-reference/input-control.md Retrieves the current day of the month (1-31) as a number. Useful for date-specific operations. ```javascript let d = day(); ``` -------------------------------- ### Load Image in WebGPU (Await) Source: https://github.com/q5js/q5.js/blob/main/lang/en/learn/image.md Loads an image using `await loadImage` in a WebGPU context, ensuring the image is fully loaded before drawing. ```js await Canvas(200); let logo = await loadImage('/q5js_logo.avif'); background(logo); ``` -------------------------------- ### Get Display Density Source: https://github.com/q5js/q5.js/blob/main/_autodocs/api-reference/canvas.md Retrieves the device pixel ratio, indicating the density of the display. Useful for high-DPI rendering. ```javascript let density = displayDensity(); console.log(`Device pixel ratio: ${density}`); ``` -------------------------------- ### Q5 Constructor Source: https://github.com/q5js/q5.js/blob/main/lang/en/learn/advanced.md Creates a new instance of Q5. You can specify the scope (global or namespace) and a parent HTML element for the canvas. ```APIDOC ## Q5.constructor Creates an [instance](https://github.com/q5js/q5.js/wiki/Instance-Mode) of Q5. Used by the global `Canvas` function. ``` @param {string | Function} [scope] - "global": (default) adds q5 functions and variables to the global scope - "namespace": does not add q5 functions or variables to the global scope @param {HTMLElement} [parent] element that the canvas will be placed inside ``` ### c2d ```js let q = new Q5('namespace'); q.createCanvas(200, 100); q.circle(100, 50, 20); ``` ```