q5play
    Preparing search index...

    Class Q5

    Index

    Constructors

    Properties

    abs acos angleMode applyMatrix asin atan atan2 background blendMode Canvas capsule ceil circle clear clearStorage color colorMode constrain copy cos createA createButton createCapture createCheckbox createColorPicker createEl createGraphics createImage createImg createInput createP createRadio createRecorder createSelect createSlider createTextImage createVideo cursor day defaultImageScale degrees deleteRecording disablePreload displayDensity displayMode dist doubleClicked ellipse ellipseMode erase exp fill filter findEl findEls floor fract frameRate fullscreen get getAudioContext getFPS getItem getTargetFrameRate hour image imageMode inFill inset inStroke jit keyIsDown keyPressed keyReleased lerp line load loadAll loadAudio loadCSV loadFont loadImage loadJSON loadPixels loadSound loadText loadXML log loge loop mag map mask max min minute mouseDragged mouseMoved mousePressed mouseReleased mouseWheel nf noCursor noErase noFill noise noiseDetail noiseMode noiseSeed noLoop norm noShadow noSmooth noStroke noTint opacity pauseRecording pixelDensity point pointerLock pop popMatrix popStyles pow push pushMatrix pushStyles radians random randomExponential randomGaussian randomGenerator randomSeed record rect rectMode redraw removeItem resetMatrix resize resizeCanvas rotate round save saveRecording scale second set shadow shadowBox shearX shearY shuffle sin smooth sq sqrt square storeItem stroke strokeCap strokeJoin strokeWeight tan text textAlign textAscent textDescent textFont textImage textLeading textSize textStyle textToPoints textWeight textWidth tint touchEnded touchMoved touchStarted translate trim updatePixels userStartAudio year canvasOptions disableFriendlyErrors errorTolerant lang MAX_CHARS MAX_ELLIPSES MAX_RECTS MAX_TEXTS MAX_TRANSFORMS modules supportsHDR version

    Methods

    Constructors

    • ⚙ Creates an instance of Q5.

      Used by the global Canvas function.

      Parameters

      • Optionalscope: string | Function
      • Optionalparent: HTMLElement

        element that the canvas will be placed inside

      Returns Q5

    Properties

    abs: (n: number) => number

    Type Declaration

      • (n: number): number
      • 🧮 Calculates the absolute value of a number.

        Parameters

        • n: number

          a number

        Returns number

        absolute value of the number

    acos: (n: number) => number
    angleMode: (mode: "degrees" | "radians") => void

    Type Declaration

      • (mode: "degrees" | "radians"): void
      • 🧮 Sets the mode for interpreting and drawing angles. Can be either 'degrees' or 'radians'.

        Parameters

        • mode: "degrees" | "radians"

          mode to set for angle interpretation

        Returns void

    applyMatrix: (
        a: number,
        b: number,
        c: number,
        d: number,
        e: number,
        f: number,
    ) => void

    Type Declaration

      • (a: number, b: number, c: number, d: number, e: number, f: number): void
      • 🦋 Applies a transformation matrix.

        Accepts a 3x3 matrix as either an array or multiple arguments.

        Note that in q5 WebGPU, the identity matrix (default) has a negative y scale to flip the y-axis to match the Canvas2D renderer.

        Parameters

        • a: number
        • b: number
        • c: number
        • d: number
        • e: number
        • f: number

        Returns void

        q5.draw = function () {
        background(0.8);

        applyMatrix(2, -1, 1, -1);
        circle(0, 0, 80);
        };
    asin: (n: number) => number
    atan: (n: number) => number
    atan2: (y: number, x: number) => number
    background: (c0: number, c1: number, c2: number, c3: number) => void

    Type Declaration

      • (c0: number, c1: number, c2: number, c3: number): void
      • 🎨 Draws over the entire canvas with a color or image.

        Like the color function, this function can accept colors in a wide range of formats: CSS color string, grayscale value, and color component values.

        Parameters

        • c0: number
        • c1: number
        • c2: number
        • c3: number

        Returns void

        await Canvas(200, 100);
        background('crimson');
        q5.draw = function () {
        background(0.5, 0.2);
        circle(mouseX, mouseY, 20);
        };
    blendMode: (val: string) => void

    Type Declaration

      • (val: string): void
      • 💅 Set the global composite operation for the canvas context.

        Not available in q5 WebGPU.

        Parameters

        • val: string

          composite operation

        Returns void

    Canvas: (w?: number, h?: number, options?: object) => Promise<HTMLCanvasElement>

    Type Declaration

      • (w?: number, h?: number, options?: object): Promise<HTMLCanvasElement>
      • ⭐ Creates a canvas element, a section of the screen your program can draw on.

        Run this function to start using q5!

        Note that in this example, the circle is located at position [0, 0], the origin of the canvas.

        Parameters

        • Optionalw: number

          width or side lengths of the canvas

        • Optionalh: number

          height of the canvas

        • Optionaloptions: object

        Returns Promise<HTMLCanvasElement>

        canvas element

        await Canvas(200, 100);
        background('silver');
        circle(0, 0, 80);
    capsule: (x1: number, y1: number, x2: number, y2: number, r: number) => void

    Type Declaration

      • (x1: number, y1: number, x2: number, y2: number, r: number): void
      • 🧑‍🎨 Draws a capsule.

        Parameters

        • x1: number

          x-coordinate of the first point

        • y1: number

          y-coordinate of the first point

        • x2: number

          x-coordinate of the second point

        • y2: number

          y-coordinate of the second point

        • r: number

          radius of the capsule semi-circle ends

        Returns void

        await Canvas(200, 100);
        background(0.8);
        strokeWeight(5);
        capsule(-60, -10, 60, 10, 10);
        q5.draw = function () {
        background(0.8);
        fill('cyan');
        strokeWeight(10);
        capsule(0, 0, mouseX, mouseY, 20);
        };
    ceil: (n: number) => number

    Type Declaration

      • (n: number): number
      • 🧮 Rounds a number up.

        Parameters

        • n: number

          a number

        Returns number

        rounded number

        await Canvas(200, 100);
        background(0.8);
        textSize(32);
        text(ceil(PI), -90, 10);
    circle: (x: number, y: number, diameter: number) => void

    Type Declaration

      • (x: number, y: number, diameter: number): void
      • 🧑‍🎨 Draws a circle.

        Parameters

        • x: number

          x-coordinate

        • y: number

          y-coordinate

        • diameter: number

          diameter of the circle

        Returns void

        await Canvas(200, 100);
        circle(0, 0, 80);
    clear: () => void

    Type Declaration

      • (): void
      • 💅 Clears the canvas, making every pixel completely transparent.

        Note that the canvas can only be seen through if it has an alpha channel.

        Returns void

        await Canvas(200, { alpha: true });

        q5.draw = function () {
        clear();
        circle((frameCount % 200) - 100, 0, 80);
        };
    clearStorage: () => void

    Type Declaration

      • (): void
      • 🛠 Clears all items from localStorage.

        Returns void

    color: (
        c0: string | number | number[] | Color,
        c1?: number,
        c2?: number,
        c3?: number,
    ) => Color

    Type Declaration

      • (
            c0: string | number | number[] | Color,
            c1?: number,
            c2?: number,
            c3?: number,
        ): Color
      • 🎨 Creates a new Color object, which is primarily useful for storing a color that your sketch will reuse or modify later.

        With the default color mode, RGB, colors have r/red, g/green, b/blue, and a/alpha components.

        The fill, stroke, and background functions accept the same wide range of color representations as this function.

        The default color format is "float", so set color components to values between 0 and 1.

        Here are some examples of valid use:

        • color(1) (grayscale)
        • color(1, 0.8) (grayscale, alpha)
        • color(1, 0, 0) (r, g, b)
        • color(1, 0, 0, 0.1) (r, g, b, a)
        • color('red') (colorName)
        • color('#ff0000') (hexColor)
        • color([1, 0, 0]) (colorComponents)

        Parameters

        • c0: string | number | number[] | Color

          color or first color component

        • Optionalc1: number

          second color component

        • Optionalc2: number

          third color component

        • Optionalc3: number

          fourth color component (alpha)

        Returns Color

        a new Color object

        await Canvas(200);
        rect(-100, -100, 100, 200);

        // ( r, g, b, a)
        let bottle = color(0.35, 0.39, 1, 0.4);
        fill(bottle);
        stroke(bottle);
        strokeWeight(30);
        circle(0, 0, 155);
        await Canvas(200);
        // (gray, alpha)
        let c = color(0.8, 0.2);

        q5.draw = function () {
        background(c);
        circle(mouseX, mouseY, 50);
        c.g = (c.g + 0.005) % 1;
        };
        await Canvas(200);

        // (r, g, b, a)
        let c = color(0, 1, 1, 0.2);

        q5.draw = function () {
        fill(c);
        circle(mouseX, mouseY, 50);
        };
    colorMode: (
        mode: "rgb" | "oklch",
        format: 1 | 255,
        gamut?: "srgb" | "display-p3",
    ) => void

    Type Declaration

      • (mode: "rgb" | "oklch", format: 1 | 255, gamut?: "srgb" | "display-p3"): void
      • 🎨 Sets the color mode for the sketch, which changes how colors are interpreted and displayed.

        Color gamut is 'display-p3' by default, if the device supports HDR.

        The default color mode is RGB in float format.

        Parameters

        • mode: "rgb" | "oklch"

          color mode

        • format: 1 | 255

          color format (1 for float, 255 for integer)

        • Optionalgamut: "srgb" | "display-p3"

          color gamut

        Returns void

        await Canvas(200);

        colorMode(RGB, 1);
        fill(1, 0, 0);
        rect(-100, -100, 66, 200);
        fill(0, 1, 0);
        rect(-34, -100, 67, 200);
        fill(0, 0, 1);
        rect(33, -100, 67, 200);
        await Canvas(200);

        colorMode(OKLCH);

        fill(0.25, 0.15, 0);
        rect(-100, -100, 100, 200);

        fill(0.75, 0.15, 0);
        rect(0, -100, 100, 200);
    constrain: (n: number, low: number, high: number) => number

    Type Declaration

      • (n: number, low: number, high: number): number
      • 🧮 Constrains a value between a minimum and maximum value.

        Parameters

        • n: number

          number to constrain

        • low: number

          lower bound

        • high: number

          upper bound

        Returns number

        constrained value

    copy: () => Image

    Type Declaration

      • (): Image
      • 🌆 Returns a copy of the image.

        Returns Image

    cos: (angle: number) => number
    createA: (href: string, text?: string) => HTMLAnchorElement

    Type Declaration

      • (href: string, text?: string): HTMLAnchorElement
      • 📑 Creates a link element.

        Parameters

        • href: string

          url

        • Optionaltext: string

          text content

        Returns HTMLAnchorElement

        await Canvas(200);

        let link = createA('https://q5js.org', 'q5.js');
        link.position(16, 42);
        link.style.fontSize = '80px';

        link.addEventListener('mouseover', () => {
        background('cyan');
        });
    createButton: (content?: string) => HTMLButtonElement

    Type Declaration

      • (content?: string): HTMLButtonElement
      • 📑 Creates a button element.

        Parameters

        • Optionalcontent: string

          text content

        Returns HTMLButtonElement

        await Canvas(200, 100);

        let btn = createButton('Click me!');

        btn.addEventListener('click', () => {
        background(random(0.4, 1));
        });
    createCapture: (
        type?: string,
        flipped?: boolean,
    ) => HTMLVideoElement & PromiseLike<HTMLVideoElement>

    Type Declaration

      • (
            type?: string,
            flipped?: boolean,
        ): HTMLVideoElement & PromiseLike<HTMLVideoElement>
      • 📑 Creates a capture from a connected camera, such as a webcam.

        The capture video element can be hidden and its content can be displayed on the canvas using the image function.

        Can preload to ensure the capture is ready to use when your sketch starts.

        Requests the highest video resolution from the user facing camera by default. The first parameter to this function can be used to specify the constraints for the capture. See getUserMedia for more info.

        Parameters

        • Optionaltype: string

          type of capture, can be only VIDEO or only AUDIO, the default is to use both video and audio

        • Optionalflipped: boolean

          whether to mirror the video vertically, true by default

        Returns HTMLVideoElement & PromiseLike<HTMLVideoElement>

        a new video element

        q5.mousePressed = function () {
        let cap = createCapture(VIDEO);
        cap.size(200, 112.5);
        canvas.remove();
        };
        let cap;
        q5.mousePressed = function () {
        cap = createCapture(VIDEO);
        cap.hide();
        };

        q5.draw = function () {
        let y = (frameCount % 200) - 100;
        image(cap, -100, y, 200, 200);
        };
        q5.mousePressed = function () {
        let cap = createCapture({
        video: { width: 640, height: 480 }
        });
        cap.size(200, 150);
        canvas.remove();
        };
    createCheckbox: (label?: string, checked?: boolean) => HTMLInputElement

    Type Declaration

      • (label?: string, checked?: boolean): HTMLInputElement
      • 📑 Creates a checkbox element.

        Use the checked property to get or set the checkbox's state.

        The label property is the text label element next to the checkbox.

        Parameters

        • Optionallabel: string

          text label placed next to the checkbox

        • Optionalchecked: boolean

          initial state

        Returns HTMLInputElement

        await Canvas(200, 100);

        let box = createCheckbox('Check me!');
        box.label.style.color = 'lime';

        box.addEventListener('input', () => {
        if (box.checked) background('lime');
        else background('black');
        });
    createColorPicker: (value?: string) => HTMLInputElement

    Type Declaration

      • (value?: string): HTMLInputElement
      • 📑 Creates a color input element.

        Use the value property to get or set the color value.

        Parameters

        • Optionalvalue: string

          initial color value

        Returns HTMLInputElement

        await Canvas(200, 100);

        let picker = createColorPicker();
        picker.value = '#fd7575';

        q5.draw = function () {
        background(picker.value);
        };
    createEl: (tag: string, content?: string) => HTMLElement

    Type Declaration

      • (tag: string, content?: string): HTMLElement
      • 📑 Creates a new HTML element and adds it to the page. createElement is an alias.

        Modify the element's CSS style to change its appearance.

        Use addEventListener to respond to events such as:

        • "click": when the element is clicked
        • "mouseover": when the mouse hovers over the element
        • "mouseout": when the mouse stops hovering over the element
        • "input": when a form element's value changes

        q5 adds some extra functionality to the elements it creates:

        • the position function makes it easy to place the element relative to the canvas
        • the size function sets the width and height of the element
        • alternatively, use the element's x, y, width, and height properties

        Parameters

        • tag: string

          tag name of the element

        • Optionalcontent: string

          content of the element

        Returns HTMLElement

        element

        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';
    createGraphics: (w: number, h: number, opt?: any) => Q5

    Type Declaration

      • (w: number, h: number, opt?: any): Q5
      • 🌆 Creates a graphics buffer.

        Graphics looping is disabled by default in q5 WebGPU. See issue #104 for details.

        Parameters

        • w: number

          width

        • h: number

          height

        • Optionalopt: any

          options

        Returns Q5

        a new Q5 graphics buffer

        await Canvas(200);

        let g = createGraphics(100);
        g.noLoop();
        g.stroke('pink');
        g.fill('red');
        g.circle(50, 50, 120);

        image(g, -50, -50, 100, 100);
    createImage: (w: number, h: number, opt?: any) => Image

    Type Declaration

      • (w: number, h: number, opt?: any): Image
      • 🌆 Creates a new image.

        Parameters

        • w: number

          width

        • h: number

          height

        • Optionalopt: any

          optional settings for the image

        Returns Image

    createImg: (src: string) => HTMLImageElement

    Type Declaration

      • (src: string): HTMLImageElement
      • 📑 Creates an image element.

        Parameters

        • src: string

          url of the image

        Returns HTMLImageElement

        await Canvas(200, 100);

        let img = createImg('/assets/q5play_logo.avif');
        img.position(0, 0).size(100, 100);
    createInput: (value?: string, type?: string) => HTMLInputElement

    Type Declaration

      • (value?: string, type?: string): HTMLInputElement
      • 📑 Creates an input element.

        Use the value property to get or set the input's value.

        Use the placeholder property to set label text that appears inside the input when it's empty.

        See MDN's input documentation for the full list of input types.

        Parameters

        • Optionalvalue: string

          initial value

        • Optionaltype: string

          text input type, can be 'text', 'password', 'email', 'number', 'range', 'search', 'tel', 'url'

        Returns HTMLInputElement

        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);
        });
    createP: (content?: string) => HTMLParagraphElement

    Type Declaration

      • (content?: string): HTMLParagraphElement
      • 📑 Creates a paragraph element.

        Parameters

        • Optionalcontent: string

          text content

        Returns HTMLParagraphElement

        await Canvas(200, 50);
        background('coral');

        let p = createP('Hello, world!');
        p.style.color = 'pink';
    createRadio: (groupName?: string) => HTMLDivElement

    Type Declaration

      • (groupName?: string): HTMLDivElement
      • 📑 Creates a radio button group.

        Use the option(label, value) function to add new radio buttons to the group.

        Use the value property to get or set the value of the selected radio button.

        Parameters

        • OptionalgroupName: string

        Returns HTMLDivElement

        await Canvas(200, 160);

        let radio = createRadio();
        radio.option('square', '1');
        radio.option('circle', '2');

        q5.draw = function () {
        background(0.8);
        if (radio.value == '1') square(-40, -40, 80);
        if (radio.value == '2') circle(0, 0, 80);
        };
    createRecorder: () => HTMLElement

    Type Declaration

      • (): HTMLElement
      • 🎞 Creates a recorder. Simply hit record to start recording!

        The following properties can be set via the recorder UI or programmatically.

        • format is set to "H.264" by default.
        • bitrate is a number in megabits per second (mbps). Its default value is determined by the height of the canvas. Increasing the bitrate will increase the quality and file size of the recording.
        • captureAudio is set to true by default. Set to false to disable audio recording.

        Note that recordings are done at a variable frame rate (VFR), which makes the output video incompatible with some editing software. For more info, see the "Recording the Canvas". wiki page.

        Returns HTMLElement

        a recorder, q5 DOM element

        await Canvas(200);

        let rec = createRecorder();
        rec.bitrate = 10;

        q5.draw = function () {
        circle(mouseX, jit(halfHeight), 10);
        };
    createSelect: (placeholder?: string) => HTMLSelectElement

    Type Declaration

      • (placeholder?: string): HTMLSelectElement
      • 📑 Creates a select element.

        Use the option(label, value) function to add new options to the select element.

        Set multiple to true to allow multiple options to be selected.

        Use the value property to get or set the selected option value.

        Use the selected property get the labels of the selected options or set the selected options by label. Can be a single string or an array of strings.

        Parameters

        • Optionalplaceholder: string

          optional placeholder text that appears before an option is selected

        Returns HTMLSelectElement

        await Canvas(200, 100);

        let sel = createSelect('Select an option');
        sel.option('Red', '#f55');
        sel.option('Green', '#5f5');

        sel.addEventListener('change', () => {
        background(sel.value);
        });
    createSlider: (
        min: number,
        max: number,
        value?: number,
        step?: number,
    ) => HTMLInputElement

    Type Declaration

      • (min: number, max: number, value?: number, step?: number): HTMLInputElement
      • 📑 Creates a slider element.

        Use the value property to get or set the slider's value.

        Use the val function to get the slider's value as a number.

        Parameters

        • min: number

          minimum value

        • max: number

          maximum value

        • Optionalvalue: number

          initial value

        • Optionalstep: number

          step size

        Returns HTMLInputElement

        await Canvas(200);

        let slider = createSlider(0, 1, 0.5, 0.1);
        slider.position(10, 10).size(180);

        q5.draw = function () {
        background(slider.val());
        };
    createTextImage: (str: string, wrapWidth?: number, lineLimit?: number) => Image

    Type Declaration

      • (str: string, wrapWidth?: number, lineLimit?: number): Image
      • 📘 Creates an image from a string of text.

        Parameters

        • str: string

          string of text

        • OptionalwrapWidth: number

          maximum line width in characters

        • OptionallineLimit: number

          maximum number of lines

        Returns Image

        an image object representing the rendered text

        await Canvas(200);
        textSize(96);

        let img = createTextImage('🐶');
        img.filter(INVERT);

        q5.draw = function () {
        image(img, -45, -90);
        };
    createVideo: (src: string) => HTMLVideoElement & PromiseLike<HTMLVideoElement>

    Type Declaration

      • (src: string): HTMLVideoElement & PromiseLike<HTMLVideoElement>
      • 📑 Creates a video element.

        Note that videos must be muted to autoplay and the play and pause functions can only be run after a user interaction.

        The video element can be hidden and its content can be displayed on the canvas using the image function.

        Parameters

        • src: string

          url of the video

        Returns HTMLVideoElement & PromiseLike<HTMLVideoElement>

        a new video element

        await Canvas(1);

        let vid = createVideo('/assets/apollo4.mp4');
        vid.size(200, 150);
        vid.autoplay = vid.muted = vid.loop = true;
        vid.controls = true;
        await Canvas(200, 150);
        let vid = createVideo('/assets/apollo4.mp4');
        vid.hide();

        q5.mousePressed = function () {
        vid.currentTime = 0;
        vid.play();
        };
        q5.draw = function () {
        rotate(mouseX / 55);
        image(vid, -100, -75, 200, 150);
        };
    cursor: (name: string, x?: number, y?: number) => void

    Type Declaration

      • (name: string, x?: number, y?: number): void
      • 🖲 Sets the cursor to a CSS cursor type or image. If an image is provided, optional x and y coordinates can specify the active point of the cursor.

        Parameters

        • name: string

          name of the cursor or the url to an image

        • Optionalx: number

          x-coordinate of the cursor's point

        • Optionaly: number

          y-coordinate of the cursor's point

        Returns void

        await Canvas(200, 100);
        cursor('pointer');
    day: () => number

    Type Declaration

      • (): number
      • 🛠 Returns the current day of the month.

        Returns number

        current day

    defaultImageScale: (scale: number) => number

    Type Declaration

      • (scale: number): number
      • 🌆 Sets the default image scale, which is applied to images when they are drawn without a specified width or height.

        By default it is 0.5 so images appear at their actual size when pixel density is 2. Images will be drawn at a consistent default size relative to the canvas regardless of pixel density.

        This function must be called before images are loaded to have an effect.

        Parameters

        • scale: number

        Returns number

        default image scale

    degrees: (radians: number) => number

    Type Declaration

      • (radians: number): number
      • 🧮 Converts radians to degrees.

        Parameters

        • radians: number

          angle in radians

        Returns number

        angle in degrees

    deleteRecording: () => void

    Type Declaration

      • (): void
      • 🎞 Discards the current recording.

        Returns void

    disablePreload: () => void

    Type Declaration

      • (): void
      • 🛠 Disables the automatic preloading of assets before draw starts looping. This allows draw to start immediately, and assets can be lazy loaded or loadAll() can be used to wait for assets to finish loading later.

        Returns void

    displayDensity: () => number

    Type Declaration

      • (): number
      • 💻 Returns the current display density.

        On most modern displays, this value will be 2 or 3.

        Returns number

        display density

        await Canvas(200, 100);
        background(0.8);
        textSize(64);
        text(displayDensity(), -90, 6);
    displayMode: (
        mode: string,
        renderQuality: string,
        scale: string | number,
    ) => void

    Type Declaration

      • (mode: string, renderQuality: string, scale: string | number): void
      • 💻 Customize how your canvas is presented.

        Parameters

        • mode: string

          NORMAL, CENTER, or MAXED

        • renderQuality: string

          SMOOTH or PIXELATED

        • scale: string | number

          can also be given as a string (for example "x2")

        Returns void

        await Canvas(50, 25);

        displayMode(CENTER, PIXELATED, 4);

        circle(0, 0, 16);
    dist: (x1: number, y1: number, x2: number, y2: number) => number

    Type Declaration

      • (x1: number, y1: number, x2: number, y2: number): number
      • 🧮 Calculates the distance between two points.

        This function also accepts two objects with x and y properties.

        Parameters

        • x1: number

          x-coordinate of the first point

        • y1: number

          y-coordinate of the first point

        • x2: number

          x-coordinate of the second point

        • y2: number

          y-coordinate of the second point

        Returns number

        distance between the points

        q5.draw = function () {
        background(0.8);
        line(0, 0, mouseX, mouseY);

        let d = dist(0, 0, mouseX, mouseY);
        text(round(d), -80, -80);
        };
    doubleClicked: () => void

    Type Declaration

      • (): void
      • 🖲 Define this function to respond to mouse double click events.

        Returns void

        await Canvas(200);
        let gray = 0.4;

        q5.doubleClicked = function () {
        background(gray % 1);
        gray += 0.1;
        };
    ellipse: (x: number, y: number, width: number, height: number) => void

    Type Declaration

      • (x: number, y: number, width: number, height: number): void
      • 🧑‍🎨 Draws an ellipse.

        Parameters

        • x: number

          x-coordinate

        • y: number

          y-coordinate

        • width: number

          width of the ellipse

        • height: number

          height of the ellipse

        Returns void

        await Canvas(200, 100);
        ellipse(0, 0, 160, 80);
    ellipseMode: (mode: string) => void

    Type Declaration

      • (mode: string): void
      • 🧑‍🎨 Set to CENTER (default), RADIUS, CORNER, or CORNERS.

        Changes how the first four inputs to ellipse, circle, and arc are interpreted.

        Parameters

        • mode: string

        Returns void

        await Canvas(200, 100);
        background(0.8);
        ellipseMode(CENTER);

        // (x, y, w, h)
        ellipse(0, 0, 100, 50);
        await Canvas(200, 100);
        background(0.8);
        ellipseMode(RADIUS);

        // (x, y, rX, rY)
        ellipse(0, 0, 50, 25);
        await Canvas(200, 100);
        background(0.8);
        ellipseMode(CORNER);

        // ( lX, tY, w, h)
        ellipse(-50, -25, 100, 50);
        await Canvas(200, 100);
        background(0.8);
        ellipseMode(CORNERS);

        // ( x1, y1, x2, y2)
        ellipse(-50, -25, 50, 25);
    erase: (fillAlpha?: number, strokeAlpha?: number) => void

    Type Declaration

      • (fillAlpha?: number, strokeAlpha?: number): void
      • 💅 Sets the canvas to erase mode, where shapes will erase what's underneath them instead of drawing over it.

        Not available in q5 WebGPU.

        Parameters

        • OptionalfillAlpha: number

          opacity level of the fill color

        • OptionalstrokeAlpha: number

          opacity level of the stroke color

        Returns void

    exp: (exponent: number) => number

    Type Declaration

      • (exponent: number): number
      • 🧮 Calculates e raised to the power of a number.

        Parameters

        • exponent: number

          power to raise e to

        Returns number

        e raised to the power of exponent

    fill: (c0: number, c1: number, c2: number, c3: number) => void

    Type Declaration

      • (c0: number, c1: number, c2: number, c3: number): void
      • 💅 Sets the fill color. The default is white.

        Like the color function, this function can accept colors in a wide range of formats: as a CSS color string, a Color object, grayscale value, or color component values.

        Parameters

        • c0: number
        • c1: number
        • c2: number
        • c3: number

        Returns void

        await Canvas(200);
        background(0.8);

        fill('red');
        circle(-20, -20, 80);

        fill('lime');
        square(-20, -20, 80);
    filter: (type: string, value?: number) => void

    Type Declaration

      • (type: string, value?: number): void
      • 🌆 Applies a filter to the image.

        See the documentation for q5's filter constants below for more info.

        A CSS filter string can also be used. https://developer.mozilla.org/docs/Web/CSS/filter

        Not applicable to WebGPU canvases.

        Parameters

        • type: string

          filter type or a CSS filter string

        • Optionalvalue: number

          optional value, depends on filter type

        Returns void

        await Canvas(200);
        let logo = await load('/q5js_logo.avif');
        logo.filter(INVERT);
        image(logo, -100, -100, 200, 200);
    findEl: (selector: string) => HTMLElement

    Type Declaration

      • (selector: string): HTMLElement
      • 📑 Finds the first element in the DOM that matches the given CSS selector.

        Alias for document.querySelector.

        Parameters

        • selector: string

        Returns HTMLElement

        element

    findEls: (selector: string) => HTMLElement[]

    Type Declaration

      • (selector: string): HTMLElement[]
      • 📑 Finds all elements in the DOM that match the given CSS selector.

        Alias for document.querySelectorAll.

        Parameters

        • selector: string

        Returns HTMLElement[]

        elements

    floor: (n: number) => number

    Type Declaration

      • (n: number): number
      • 🧮 Rounds a number down.

        Parameters

        • n: number

          a number

        Returns number

        rounded number

        await Canvas(200, 100);
        background(0.8);
        textSize(32);
        text(floor(-PI), -90, 10);
    fract: (n: number) => number

    Type Declaration

      • (n: number): number
      • 🧮 Calculates the fractional part of a number.

        Parameters

        • n: number

          a number

        Returns number

        fractional part of the number

    frameRate: (hertz?: number) => number

    Type Declaration

      • (hertz?: number): number
      • 💻 Sets the target frame rate or gets an approximation of the sketch's current frame rate.

        Even when the sketch is running at a consistent frame rate, the current frame rate value will fluctuate. Use your web browser's developer tools for more accurate performance analysis.

        Parameters

        • Optionalhertz: number

          target frame rate, default is 60

        Returns number

        current frame rate

        q5.draw = function () {
        background(0.8);

        if (mouseIsPressed) frameRate(10);
        else frameRate(60);

        circle((frameCount % 200) - 100, 0, 80);
        };
        q5.draw = function () {
        background(0.8);
        textSize(64);
        text(round(frameRate()), -35, 20);
        };
    fullscreen: (v?: boolean) => void

    Type Declaration

      • (v?: boolean): void
      • 💻 Enables or disables fullscreen mode.

        Parameters

        • Optionalv: boolean

          boolean indicating whether to enable or disable fullscreen mode

        Returns void

    get: (x: number, y: number, w?: number, h?: number) => Image | number[]

    Type Declaration

      • (x: number, y: number, w?: number, h?: number): Image | number[]
      • 🌆 Retrieves a subsection of an image or canvas as a new Q5 Image or the color of a pixel in the image or canvas.

        If only x and y are specified, this function returns the color of the pixel at the given coordinate in [R, G, B, A] array format. If loadPixels has never been run, it's run by this function.

        If you make changes to the canvas or image, you must call loadPixels before using this function to get current color data.

        Not applicable to WebGPU canvases.

        Parameters

        • x: number
        • y: number
        • Optionalw: number

          width of the area, default is 1

        • Optionalh: number

          height of the area, default is 1

        Returns Image | number[]

        await Canvas(200);

        let logo = await load('/q5js_logo.avif');

        let cropped = logo.get(256, 256, 512, 512);
        image(cropped, -100, -100, 200, 200);
    getAudioContext: () => void | AudioContext

    Type Declaration

      • (): void | AudioContext
      • 🔊 Returns the AudioContext in use or undefined if it doesn't exist.

        Returns void | AudioContext

        AudioContext instance

    getFPS: () => number

    Type Declaration

      • (): number
      • 💻 Gets the current FPS, in terms of how many frames could be generated in one second, which can be higher than the target frame rate.

        Use your web browser's developer tools for more in-depth performance analysis.

        Returns number

        frames per second

        q5.draw = function () {
        background(0.8);
        frameRate(1);
        textSize(64);

        text(getFPS(), -92, 20);
        };
    getItem: (key: string) => string

    Type Declaration

      • (key: string): string
      • 🛠 Retrieves an item from localStorage.

        Parameters

        • key: string

          key of the item to retrieve

        Returns string

        value of the retrieved item

    getTargetFrameRate: () => number

    Type Declaration

      • (): number
      • 💻 The desired frame rate of the sketch.

        Returns number

        target frame rate

        q5.draw = function () {
        background(0.8);
        textSize(64);

        text(getTargetFrameRate(), -35, 20);
        };
    hour: () => number

    Type Declaration

      • (): number
      • 🛠 Returns the current hour.

        Returns number

        current hour

    image: () => void

    Type Declaration

      • (): void
      • 🌆 Draws an image or video frame to the canvas.

        Returns void

        await Canvas(200);

        let logo = load('/q5js_logo.avif');

        q5.draw = function () {
        image(logo, -100, -100, 200, 200);
        };
        await Canvas(200);

        let logo = load('/q5js_logo.avif');

        q5.draw = function () {
        image(logo, -100, -100, 200, 200, 256, 256, 512, 512);
        };
    imageMode: (mode: string) => void

    Type Declaration

      • (mode: string): void
      • 🌆 Set to CORNER (default), CORNERS, or CENTER.

        Changes how inputs to image are interpreted.

        Parameters

        • mode: string

        Returns void

        await Canvas(200);
        let logo = load('/q5js_logo.avif');

        q5.draw = function () {
        imageMode(CORNER);

        // ( img, x, y, w, h)
        image(logo, -50, -50, 100, 100);
        };
        await Canvas(200);
        let logo = load('/q5js_logo.avif');

        q5.draw = function () {
        imageMode(CENTER);

        // (img, cX, cY, w, h)
        image(logo, 0, 0, 100, 100);
        };
        await Canvas(200);
        let logo = load('/q5js_logo.avif');

        q5.draw = function () {
        imageMode(CORNERS);

        // ( img, x1, y1, x2, y2)
        image(logo, -50, -50, 50, 50);
        };
    inFill: (x: number, y: number) => boolean

    Type Declaration

      • (x: number, y: number): boolean
      • 💅 Checks if a given point is within the current path's fill area.

        Not available in q5 WebGPU.

        Parameters

        • x: number

          x-coordinate of the point

        • y: number

          y-coordinate of the point

        Returns boolean

        true if the point is within the fill area, false otherwise

    inset: (
        sx: number,
        sy: number,
        sw: number,
        sh: number,
        dx: number,
        dy: number,
        dw: number,
        dh: number,
    ) => void

    Type Declaration

      • (
            sx: number,
            sy: number,
            sw: number,
            sh: number,
            dx: number,
            dy: number,
            dw: number,
            dh: number,
        ): void
      • 🌆 Displays a region of the image on another region of the image. Can be used to create a detail inset, aka a magnifying glass effect.

        Parameters

        • sx: number

          x-coordinate of the source region

        • sy: number

          y-coordinate of the source region

        • sw: number

          width of the source region

        • sh: number

          height of the source region

        • dx: number

          x-coordinate of the destination region

        • dy: number

          y-coordinate of the destination region

        • dw: number

          width of the destination region

        • dh: number

          height of the destination region

        Returns void

        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);
    inStroke: (x: number, y: number) => boolean

    Type Declaration

      • (x: number, y: number): boolean
      • 💅 Checks if a given point is within the current path's stroke.

        Not available in q5 WebGPU.

        Parameters

        • x: number

          x-coordinate of the point

        • y: number

          y-coordinate of the point

        Returns boolean

        true if the point is within the stroke, false otherwise

    jit: (amount?: number) => number

    Type Declaration

      • (amount?: number): number
      • 🧮 Generates a random number within a symmetric range around zero.

        Can be used to create a jitter effect (random displacement).

        Equivalent to random(-amount, amount).

        Parameters

        • Optionalamount: number

          absolute maximum amount of jitter, default is 1

        Returns number

        random number between -val and val

        q5.draw = function () {
        circle(mouseX + jit(3), mouseY + jit(3), 5);
        };
        await Canvas(200);

        q5.draw = function () {
        circle(jit(50), 0, random(50));
        };
    keyIsDown: (key: string) => boolean

    Type Declaration

      • (key: string): boolean
      • 🖲 Returns true if the user is pressing the specified key, false otherwise. Accepts case-insensitive key names.

        Parameters

        • key: string

          key to check

        Returns boolean

        true if the key is pressed, false otherwise

        q5.draw = function () {
        background(0.8);

        if (keyIsDown('f') && keyIsDown('j')) {
        rect(-50, -50, 100, 100);
        }
        };
    keyPressed: () => void

    Type Declaration

      • (): void
      • 🖲 Define this function to respond to key down events.

        Returns void

        await Canvas(200);
        let gray = 0.4;

        q5.keyPressed = function () {
        background(gray % 1);
        gray += 0.1;
        };
    keyReleased: () => void

    Type Declaration

      • (): void
      • 🖲 Define this function to respond to key up events.

        Returns void

        await Canvas(200);
        let gray = 0.4;

        q5.keyReleased = function () {
        background(gray % 1);
        gray += 0.1;
        };
    lerp: (start: number, stop: number, amt: number) => number

    Type Declaration

      • (start: number, stop: number, amt: number): number
      • 🧮 Calculates a number between two numbers at a specific increment.

        Parameters

        • start: number

          first number

        • stop: number

          second number

        • amt: number

          amount to interpolate between the two values

        Returns number

        interpolated number

    line: (x1: number, y1: number, x2: number, y2: number) => void

    Type Declaration

      • (x1: number, y1: number, x2: number, y2: number): void
      • 🧑‍🎨 Draws a line on the canvas.

        To draw lines with rounded stroke caps, use capsule instead.

        Parameters

        • x1: number

          x-coordinate of the first point

        • y1: number

          y-coordinate of the first point

        • x2: number

          x-coordinate of the second point

        • y2: number

          y-coordinate of the second point

        Returns void

        await Canvas(200, 100);
        stroke('lime');
        line(-80, -30, 80, 30);
    load: (...urls: string[]) => PromiseLike<any[]>

    Type Declaration

      • (...urls: string[]): PromiseLike<any[]>
      • 🛠 Loads a file or multiple files.

        File type is determined by file extension. q5 supports loading text, json, csv, font, audio, and image files.

        By default, assets are loaded in parallel before q5 runs draw. Use await to wait for assets to load.

        Parameters

        • ...urls: string[]

        Returns PromiseLike<any[]>

        a promise that resolves with objects

        await Canvas(200);

        let logo = load('/q5js_logo.avif');

        q5.draw = function () {
        image(logo, -100, -100, 200, 200);
        };
        await Canvas(200);
        background(0.8);

        await load('/assets/Robotica.ttf');

        textSize(28);
        text('Hello, world!', -97, 100);
        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();
        };
        //
        await Canvas(200);
        background(0.8);
        textSize(32);

        let xml = await load('/assets/animals.xml');
        let mammals = xml.querySelectorAll('mammal');
        let y = -90;
        for (let mammal of mammals) {
        text(mammal.textContent, -90, (y += 32));
        }
    loadAll: () => PromiseLike<any[]>

    Type Declaration

      • (): PromiseLike<any[]>
      • 🛠 Wait for any assets that started loading to finish loading. By default q5 runs this before looping draw (which is called preloading), but it can be used even after draw starts looping.

        Returns PromiseLike<any[]>

        a promise that resolves with loaded objects

    loadAudio: (url: string) => HTMLAudioElement & PromiseLike<HTMLAudioElement>

    Type Declaration

      • (url: string): HTMLAudioElement & PromiseLike<HTMLAudioElement>
      • 🔊 Loads audio data from a file and returns an HTMLAudioElement.

        Audio is considered loaded when the canplaythrough event is fired.

        Note that audio can only be played after the first user interaction with the page!

        Parameters

        • url: string

        Returns HTMLAudioElement & PromiseLike<HTMLAudioElement>

        await Canvas(200);

        let audio = loadAudio('/assets/retro.flac');
        audio.volume = 0.4;

        q5.mousePressed = function () {
        audio.play();
        };
    loadCSV: (url: string) => object[] & PromiseLike<object[]>

    Type Declaration

      • (url: string): object[] & PromiseLike<object[]>
      • 🛠 Loads a CSV file from the specified url.

        Using await to get the loaded CSV as an array of objects is recommended.

        Parameters

        • url: string

          CSV file

        Returns object[] & PromiseLike<object[]>

        an array of objects containing the loaded CSV

    loadFont: (url: string) => FontFace & PromiseLike<FontFace>

    Type Declaration

      • (url: string): FontFace & PromiseLike<FontFace>
      • 📘 Loads a font from a URL.

        The first example below loads Robotica.

        The second example loads Pacifico from Google fonts.

        By default, assets are loaded in parallel before q5 runs draw. Use await to wait for a font to load.

        Fonts in MSDF format with the file ending "-msdf.json" can be used for high performance text rendering. Make your own using the MSDF font converter.

        If no fonts are loaded, q5 WebGPU will lazy load the default MSDF font from q5js.org. Until it is loaded, the system's default sans-serif font will be used via textImage.

        Parameters

        • url: string

          URL of the font to load

        Returns FontFace & PromiseLike<FontFace>

        font

        await Canvas(200, 56);

        await loadFont('/assets/Robotica.ttf');

        fill('skyblue');
        textSize(64);
        text('Hello!', -98, 24);
        await Canvas(200, 74);

        loadFont('fonts.googleapis.com/css2?family=Pacifico');

        q5.draw = function () {
        fill('hotpink');
        textSize(68);
        text('Hello!', -98, 31);
        };
        //
        await Canvas(200, 74);

        await loadFont('sans-serif'); // msdf

        fill('white');
        textSize(68);
        text('Hello!', -98, 31);
    loadImage: (url: string) => Image & PromiseLike<Image>

    Type Declaration

      • (url: string): Image & PromiseLike<Image>
      • 🌆 Loads an image from a URL.

        By default, assets are loaded in parallel before q5 runs draw. Use await to wait for an image to load.

        Parameters

        • url: string

          url of the image to load

        Returns Image & PromiseLike<Image>

        image

        await Canvas(200);

        let logo = loadImage('/q5js_logo.avif');

        q5.draw = function () {
        background(logo);
        };
        await Canvas(200);

        let logo = await loadImage('/q5js_logo.avif');
        background(logo);
    loadJSON: (url: string) => any

    Type Declaration

      • (url: string): any
      • 🛠 Loads a JSON file from the specified url.

        Using await to get the loaded JSON object or array is recommended.

        Parameters

        • url: string

          JSON file

        Returns any

        an object or array containing the loaded JSON

    loadPixels: () => void

    Type Declaration

      • (): void
      • 🌆 Loads pixel data into pixels from the canvas or image.

        The example below sets some pixels' green channel to a random value.

        Not applicable to WebGPU canvases.

        Returns void

        await Canvas(200);
        frameRate(5);
        let icon = load('/q5js_icon.png');

        q5.draw = function () {
        icon.loadPixels();
        for (let i = 0; i < icon.pixels.length; i += 16) {
        icon.pixels[i + 1] = random(1);
        }
        icon.updatePixels();
        background(icon);
        };
    loadSound: (url: string) => Sound & PromiseLike<Sound>

    Type Declaration

      • (url: string): Sound & PromiseLike<Sound>
      • 🔊 Loads audio data from a file and returns a Sound object.

        Use functions like play, pause, and stop to control playback. Note that sounds can only be played after the first user interaction with the page!

        Set volume to a value between 0 (silent) and 1 (full volume). Set pan to a value between -1 (left) and 1 (right) to adjust the sound's stereo position. Set loop to true to loop the sound.

        Use loaded, paused, and ended to check the sound's status.

        The entire sound file must be loaded before playback can start, use await to wait for a sound to load. To stream larger audio files use the loadAudio function instead.

        Parameters

        • url: string

          sound file

        Returns Sound & PromiseLike<Sound>

        sound

        await Canvas(200);

        let sound = loadSound('/assets/jump.wav');
        sound.volume = 0.3;

        q5.mousePressed = function () {
        sound.play();
        };
    loadText: (url: string) => object & PromiseLike<string>

    Type Declaration

      • (url: string): object & PromiseLike<string>
      • 🛠 Loads a text file from the specified url.

        Using await to get the loaded text as a string is recommended.

        Parameters

        • url: string

          text file

        Returns object & PromiseLike<string>

        an object containing the loaded text in the property obj.text or use await to get the text string directly

    loadXML: (url: string) => object & PromiseLike<Element>

    Type Declaration

      • (url: string): object & PromiseLike<Element>
      • 🛠 Loads an xml file from the specified url.

        Using await to get the loaded XML Element is recommended.

        Parameters

        • url: string

          xml file

        Returns object & PromiseLike<Element>

        an object containing the loaded XML Element in a property called obj.DOM or use await to get the XML Element directly

        await Canvas(200);
        background(0.8);
        textSize(32);

        let xml = await load('/assets/animals.xml');
        let mammals = xml.querySelectorAll('mammal');
        let y = -90;
        for (let mammal of mammals) {
        text(mammal.textContent, -90, (y += 32));
        }
    log: (message: any) => void

    Type Declaration

      • (message: any): void
      • ⭐ Logs a message to the JavaScript console.

        To view the console, open your browser's web developer tools via the keyboard shortcut Ctrl + Shift + i or command + option + i, then click the "Console" tab.

        Use log when you're curious about what your code is doing!

        Parameters

        • message: any

        Returns void

        q5.draw = function () {
        circle(mouseX, mouseY, 80);
        log('The mouse is at:', mouseX, mouseY);
        };
    loge: (n: number) => number

    Type Declaration

      • (n: number): number
      • 🧮 Calculates the natural logarithm (base e) of a number.

        Parameters

        • n: number

          a number

        Returns number

        natural logarithm of the number

    loop: () => void

    Type Declaration

      • (): void
      • 💻 Starts the draw loop again if it was stopped.

        Returns void

        await Canvas(200);
        noLoop();

        q5.draw = function () {
        circle(frameCount * 5 - 100, 0, 80);
        };
        q5.mousePressed = function () {
        loop();
        };
    mag: (val1: number, val2: number) => number
    map: (
        val: number,
        start1: number,
        stop1: number,
        start2: number,
        stop2: number,
    ) => number

    Type Declaration

      • (
            val: number,
            start1: number,
            stop1: number,
            start2: number,
            stop2: number,
        ): number
      • 🧮 Maps a number from one range to another.

        Parameters

        • val: number

          incoming value to be converted

        • start1: number

          lower bound of the value's current range

        • stop1: number

          upper bound of the value's current range

        • start2: number

          lower bound of the value's target range

        • stop2: number

          upper bound of the value's target range

        Returns number

        mapped value

    mask: (img: Image) => void

    Type Declaration

      • (img: Image): void
      • 🌆 Masks the image with another image.

        Parameters

        • img: Image

          image to use as a mask

        Returns void

    max: (...args: number[]) => number

    Type Declaration

      • (...args: number[]): number
      • 🧮 Returns the largest value in a sequence of numbers.

        Parameters

        • ...args: number[]

          numbers to compare

        Returns number

        maximum

        q5.draw = function () {
        background(max(-mouseX / 100, 0.5));
        circle(max(mouseX, 0), 0, 80);
        };
    min: (...args: number[]) => number

    Type Declaration

      • (...args: number[]): number
      • 🧮 Returns the smallest value in a sequence of numbers.

        Parameters

        • ...args: number[]

          numbers to compare

        Returns number

        minimum

        q5.draw = function () {
        background(min(-mouseX / 100, 0.5));
        circle(min(mouseX, 0), 0, 80);
        };
    minute: () => number

    Type Declaration

      • (): number
      • 🛠 Returns the current minute.

        Returns number

        current minute

    mouseDragged: () => void

    Type Declaration

      • (): void
      • 🖲 Define this function to respond to mouse drag events.

        Dragging the mouse is defined as moving the mouse while a mouse button is pressed.

        Returns void

        await Canvas(200);
        let gray = 0.4;

        q5.mouseDragged = function () {
        background(gray % 1);
        gray += 0.005;
        };
    mouseMoved: () => void

    Type Declaration

      • (): void
      • 🖲 Define this function to respond to mouse move events.

        On touchscreen devices this function is not called when the user drags their finger on the screen.

        Returns void

        await Canvas(200);
        let gray = 0.4;

        q5.mouseMoved = function () {
        background(gray % 1);
        gray += 0.005;
        };
    mousePressed: () => void

    Type Declaration

      • (): void
      • 🖲 Define this function to respond to mouse down events.

        Returns void

        await Canvas(200);
        let gray = 0.4;

        q5.mousePressed = function () {
        background(gray % 1);
        gray += 0.1;
        };
    mouseReleased: () => void

    Type Declaration

      • (): void
      • 🖲 Define this function to respond to mouse up events.

        Returns void

        await Canvas(200);
        let gray = 0.4;

        q5.mouseReleased = function () {
        background(gray % 1);
        gray += 0.1;
        };
    mouseWheel: (event: any) => void

    Type Declaration

      • (event: any): void
      • 🖲 Define this function to respond to mouse wheel events.

        event.deltaX and event.deltaY are the horizontal and vertical scroll amounts, respectively.

        Return true to allow the default behavior of scrolling the page.

        Parameters

        • event: any

        Returns void

        let x = 0;
        let y = 0;
        q5.draw = function () {
        circle(x, y, 10);
        };
        q5.mouseWheel = function (e) {
        x += e.deltaX;
        y += e.deltaY;
        return false;
        };
    nf: {
        (num: number, digits: number): string;
        (num: number, digits: number): string;
    }

    Type Declaration

      • (num: number, digits: number): string
      • 📘 Number formatter, can be used to display a number as a string with a specified number of digits before and after the decimal point, optionally adding padding with zeros.

        Parameters

        • num: number
        • digits: number

        Returns string

        a string representation of the number, formatted accordingly

        await Canvas(200, 100);
        background(0.8);

        textSize(32);
        text(nf(PI, 4, 5), -90, 10);
      • (num: number, digits: number): string
      • 🛠 nf is short for number format. It formats a number to a string with a specified number of digits.

        Parameters

        • num: number

          number to format

        • digits: number

          number of digits to format to

        Returns string

        formatted number

        await Canvas(200, 100);
        background(0.8);

        textSize(32);
        text(nf(PI, 4, 5), -90, 10);
    noCursor: () => void

    Type Declaration

      • (): void
      • 🖲 Hides the cursor within the bounds of the canvas.

        Returns void

        await Canvas(200, 100);
        noCursor();
    noErase: () => void

    Type Declaration

      • (): void
      • 💅 Resets the canvas from erase mode to normal drawing mode.

        Not available in q5 WebGPU.

        Returns void

    noFill: () => void

    Type Declaration

      • (): void
      • 💅 After calling this function, drawing will not be filled.

        Returns void

        await Canvas(200);
        background(0.8);

        noFill();

        stroke('red');
        circle(-20, -20, 80);
        stroke('lime');
        square(-20, -20, 80);
    noise: (x?: number, y?: number, z?: number) => number

    Type Declaration

      • (x?: number, y?: number, z?: number): number
      • 🧮 Generates a noise value based on the x, y, and z inputs.

        Uses Perlin Noise by default.

        Parameters

        • Optionalx: number

          x-coordinate input

        • Optionaly: number

          y-coordinate input

        • Optionalz: number

          z-coordinate input

        Returns number

        a noise value

        q5.draw = function () {
        background(0.8);
        let n = noise(frameCount * 0.01);
        circle(0, 0, n * 200);
        };
        q5.draw = function () {
        background(0.8);
        let t = (frameCount + mouseX) * 0.02;
        for (let x = -5; x < 220; x += 10) {
        let n = noise(t, x * 0.1);
        circle(x - 100, 0, n * 40);
        }
        };
        q5.draw = function () {
        noStroke();
        let t = millis() * 0.002;
        for (let x = -100; x < 100; x += 5) {
        for (let y = -100; y < 100; y += 5) {
        fill(noise(t, (mouseX + x) * 0.05, y * 0.05));
        square(x, y, 5);
        }
        }
        };
    noiseDetail: (lod: number, falloff: number) => void

    Type Declaration

      • (lod: number, falloff: number): void
      • 🧮 Sets the level of detail for noise generation.

        Parameters

        • lod: number

          level of detail (number of octaves)

        • falloff: number

          falloff rate for each octave

        Returns void

    noiseMode: (mode: "perlin" | "simplex" | "blocky") => void

    Type Declaration

      • (mode: "perlin" | "simplex" | "blocky"): void
      • 🧮 Sets the noise generation mode.

        Only the default mode, "perlin", is included in q5.js. Use of the other modes requires the q5-noiser module.

        Parameters

        • mode: "perlin" | "simplex" | "blocky"

          noise generation mode

        Returns void

    noiseSeed: (seed: number) => void

    Type Declaration

      • (seed: number): void
      • 🧮 Sets the seed value for noise generation.

        Parameters

        • seed: number

          seed value

        Returns void

    noLoop: () => void

    Type Declaration

      • (): void
      • 💻 Stops the draw loop.

        Returns void

        q5.draw = function () {
        circle(frameCount * 5 - 100, 0, 80);
        noLoop();
        };
    norm: (n: number, start: number, stop: number) => number

    Type Declaration

      • (n: number, start: number, stop: number): number
      • 🧮 Normalizes a number from another range into a value between 0 and 1.

        Parameters

        • n: number

          number to normalize

        • start: number

          lower bound of the range

        • stop: number

          upper bound of the range

        Returns number

        normalized number

    noShadow: () => void

    Type Declaration

      • (): void
      • 💅 Disables the shadow effect.

        Not available in q5 WebGPU.

        Returns void

    noSmooth: () => void

    Type Declaration

      • (): void
      • 🌆 Disables smooth image rendering for a pixelated look.

        This setting is applied to images when they're loaded.

        Returns void

        await Canvas(200);
        noSmooth();

        let icon = await load('/q5js_icon.png');
        image(icon, -100, -100, 200, 200);
    noStroke: () => void

    Type Declaration

      • (): void
      • 💅 After calling this function, drawing will not have a stroke (outline).

        Returns void

        await Canvas(200);
        background(0.8);
        fill(0.14);
        stroke('red');
        circle(-20, -20, 80);

        noStroke();
        square(-20, -20, 80);
    noTint: () => void

    Type Declaration

      • (): void
      • 🌆 Images drawn after this function is run will not be tinted.

        Returns void

    opacity: (alpha: number) => void

    Type Declaration

      • (alpha: number): void
      • 💅 Sets the global opacity, which affects all subsequent drawing operations, except background. Default is 1, fully opaque.

        In q5 WebGPU this function only affects images.

        Parameters

        • alpha: number

          opacity level, ranging from 0 to 1

        Returns void

        await Canvas(200);
        background(0.8);

        opacity(1);
        circle(-20, -20, 80);

        opacity(0.2);
        square(-20, -20, 80);
    pauseRecording: () => void

    Type Declaration

      • (): void
      • 🎞 Pauses the canvas recording, if one is in progress.

        Returns void

    pixelDensity: (v: number) => number

    Type Declaration

      • (v: number): number
      • 💻 Sets the pixel density of the canvas.

        Parameters

        • v: number

          pixel density value

        Returns number

        pixel density

        await Canvas(200, 100);
        background(0.8);
        pixelDensity(1);
        circle(0, 0, 80);
    point: (x: number, y: number) => void

    Type Declaration

      • (x: number, y: number): void
      • 🧑‍🎨 Draws a point on the canvas.

        Parameters

        • x: number

          x-coordinate

        • y: number

          y-coordinate

        Returns void

        await Canvas(200, 100);
        stroke('white');
        point(-25, 0);

        strokeWeight(10);
        point(25, 0);
    pointerLock: (unadjustedMovement: boolean) => void

    Type Declaration

      • (unadjustedMovement: boolean): void
      • 🖲 Requests that the pointer be locked to the document body, hiding the cursor and allowing for unlimited movement.

        Operating systems enable mouse acceleration by default, which is useful when you sometimes want slow precise movement (think about you might use a graphics package), but also want to move great distances with a faster mouse movement (think about scrolling, and selecting several files). For some games however, raw mouse input data is preferred for controlling camera rotation — where the same distance movement, fast or slow, results in the same rotation.

        To exit pointer lock mode, call document.exitPointerLock().

        Parameters

        • unadjustedMovement: boolean

          set to true to disable OS-level mouse acceleration and access raw mouse input

        Returns void

        q5.draw = function () {
        circle(mouseX / 10, mouseY / 10, 10);
        };

        q5.doubleClicked = function () {
        if (!document.pointerLockElement) {
        pointerLock();
        } else {
        document.exitPointerLock();
        }
        };
    pop: () => void

    Type Declaration

      • (): void
      • 🦋 Restores the previously saved drawing style settings and transformations.

        Returns void

        await Canvas(200);

        push();
        fill('blue');
        translate(50, 50);
        circle(0, 0, 80);
        pop();

        square(0, 0, 50);
    popMatrix: () => void

    Type Declaration

      • (): void
      • 🦋 Restores the previously saved transformation matrix.

        Returns void

        await Canvas(200);
        background(0.8);

        pushMatrix();
        rotate(QUARTER_PI);
        ellipse(0, 0, 120, 40);
        popMatrix();

        ellipse(0, 0, 120, 40);
    popStyles: () => void

    Type Declaration

      • (): void
      • 💅 Restores the previously saved drawing style settings.

        Returns void

        await Canvas(200);
        background(0.8);

        pushStyles();
        fill('blue');
        circle(-50, -50, 80);

        popStyles();
        circle(50, 50, 80);
    pow: (base: number, exponent: number) => number

    Type Declaration

      • (base: number, exponent: number): number
      • 🧮 Calculates the value of a base raised to a power.

        For example, pow(2, 3) calculates 2 _ 2 _ 2 which is 8.

        Parameters

        • base: number

          base

        • exponent: number

          exponent

        Returns number

        base raised to the power of exponent

    push: () => void

    Type Declaration

      • (): void
      • 🦋 Saves the current drawing style settings and transformations.

        Returns void

        await Canvas(200);

        push();
        fill('blue');
        translate(50, 50);
        circle(0, 0, 80);
        pop();

        square(0, 0, 50);
    pushMatrix: () => void

    Type Declaration

      • (): void
      • 🦋 Saves the current transformation matrix.

        Returns void

        await Canvas(200);
        background(0.8);

        pushMatrix();
        rotate(QUARTER_PI);
        ellipse(0, 0, 120, 40);
        popMatrix();

        ellipse(0, 0, 120, 40);
    pushStyles: () => void

    Type Declaration

      • (): void
      • 💅 Saves the current drawing style settings.

        This includes the fill, stroke, stroke weight, tint, image mode, rect mode, ellipse mode, text size, text align, text baseline, and shadow settings.

        Returns void

        await Canvas(200);
        background(0.8);

        pushStyles();
        fill('blue');
        circle(-50, -50, 80);

        popStyles();
        circle(50, 50, 80);
    radians: (degrees: number) => number

    Type Declaration

      • (degrees: number): number
      • 🧮 Converts degrees to radians.

        Parameters

        • degrees: number

          angle in degrees

        Returns number

        angle in radians

    random: (low?: number | any[], high?: number) => any

    Type Declaration

      • (low?: number | any[], high?: number): any
      • 🧮 Generates a random value.

        • If no inputs are provided, returns a number between 0 and 1.
        • If one numerical input is provided, returns a number between 0 and the provided value.
        • If two numerical inputs are provided, returns a number between the two values.
        • If an array is provided, returns a random element from the array.

        Return value can be the lower bound but can never exactly be the upper bound.

        Parameters

        • Optionallow: number | any[]

          lower bound (inclusive) or an array

        • Optionalhigh: number

          upper bound (exclusive)

        Returns any

        a random number or element

        await Canvas(200);
        background(0.8);
        frameRate(5);

        q5.draw = function () {
        circle(0, 0, random(200));
        };
        q5.draw = function () {
        circle(random(-100, 100), random(-10, 10), 10);
        };
    randomExponential: () => number

    Type Declaration

      • (): number
      • 🧮 Generates a random number following an exponential distribution.

        Returns number

        a random number following an exponential distribution

    randomGaussian: (mean: number, std: number) => number

    Type Declaration

      • (mean: number, std: number): number
      • 🧮 Generates a random number following a Gaussian (normal) distribution.

        Parameters

        • mean: number

          mean (center) of the distribution

        • std: number

          standard deviation (spread or "width") of the distribution

        Returns number

        a random number following a Gaussian distribution

    randomGenerator: (method: any) => void

    Type Declaration

      • (method: any): void
      • 🧮 Sets the random number generation method.

        Parameters

        • method: any

          method to use for random number generation

        Returns void

    randomSeed: (seed: number) => void

    Type Declaration

      • (seed: number): void
      • 🧮 Sets the seed for the random number generator.

        Parameters

        • seed: number

          seed value

        Returns void

    record: () => void

    Type Declaration

      • (): void
      • 🎞 Starts recording the canvas or resumes recording if it was paused.

        If no recorder exists, one is created but not displayed.

        Returns void

    rect: (x: number, y: number, w: number, h: number, rounded?: number) => void

    Type Declaration

      • (x: number, y: number, w: number, h: number, rounded?: number): void
      • 🧑‍🎨 Draws a rectangle or a rounded rectangle.

        Also accepts 8 parameters to specify a corner radius for each corner, in the order: top-left, top-right, bottom-right, bottom-left.

        Parameters

        • x: number

          x-coordinate

        • y: number

          y-coordinate

        • w: number

          width of the rectangle

        • h: number

          height of the rectangle

        • Optionalrounded: number

          radius for all corners

        Returns void

        await Canvas(200);
        background(0.8);

        rect(-70, -80, 40, 60);
        rect(-20, -30, 40, 60, 10);
        rect(30, 20, 40, 60, 20, 4, 0, 8);
    rectMode: (mode: string) => void

    Type Declaration

      • (mode: string): void
      • 🧑‍🎨 Set to CORNER (default), CENTER, RADIUS, or CORNERS.

        Changes how the first four inputs to rect and square are interpreted.

        Parameters

        • mode: string

        Returns void

        await Canvas(200, 100);
        background(0.8);
        rectMode(CORNER);

        // ( x, y, w, h)
        rect(-50, -25, 100, 50);
        await Canvas(200, 100);
        background(0.8);
        rectMode(CENTER);

        // (cX, cY, w, h)
        rect(0, 0, 100, 50);
        await Canvas(200, 100);
        background(0.8);
        rectMode(RADIUS);

        // (cX, cY, rX, rY)
        rect(0, 0, 50, 25);
        await Canvas(200, 100);
        background(0.8);
        rectMode(CORNERS);

        // ( x1, y1, x2, y2)
        rect(-50, -25, 50, 25);
    redraw: (n?: number) => void

    Type Declaration

      • (n?: number): void
      • 💻 Redraws the canvas n times. If no input parameter is provided, it calls the draw function once.

        This is an async function.

        Parameters

        • Optionaln: number

          number of times to redraw the canvas, default is 1

        Returns void

        await Canvas(200);
        noLoop();

        q5.draw = function () {
        circle(frameCount * 5 - 100, 0, 80);
        };
        q5.mousePressed = function () {
        redraw(10);
        };
    removeItem: (key: string) => void

    Type Declaration

      • (key: string): void
      • 🛠 Removes an item from localStorage.

        Parameters

        • key: string

          key of the item to remove

        Returns void

    resetMatrix: () => void

    Type Declaration

      • (): void
      • 🦋 Resets the transformation matrix.

        q5 runs this function before every time the draw function is run, so that transformations don't carry over to the next frame.

        Returns void

        await Canvas(200);
        background(0.8);

        translate(50, 50);
        circle(0, 0, 80);

        resetMatrix();
        square(0, 0, 50);
    resize: (w: number, h: number) => void

    Type Declaration

      • (w: number, h: number): void
      • 🌆 Resizes the image.

        Parameters

        • w: number

          new width

        • h: number

          new height

        Returns void

        await Canvas(200);

        let logo = await load('/q5js_logo.avif');

        logo.resize(128, 128);
        image(logo, -100, -100, 200, 200);
    resizeCanvas: (w: number, h: number) => void

    Type Declaration

      • (w: number, h: number): void
      • 💻 Resizes the canvas to the specified width and height.

        Parameters

        • w: number

          width of the canvas

        • h: number

          height of the canvas

        Returns void

        await Canvas(200, 100);

        q5.draw = function () {
        background(0.8);
        };

        q5.mousePressed = function () {
        resizeCanvas(200, 200);
        };
    rotate: (angle: number) => void

    Type Declaration

      • (angle: number): void
      • 🦋 Rotates the drawing context.

        Parameters

        • angle: number

          rotation angle in radians

        Returns void

        q5.draw = function () {
        background(0.8);

        rotate(mouseX / 50);

        rectMode(CENTER);
        square(0, 0, 120);
        };
    round: (n: number, d?: number) => number

    Type Declaration

      • (n: number, d?: number): number
      • 🧮 Rounds a number.

        Parameters

        • n: number

          number to round

        • Optionald: number

          number of decimal places to round to

        Returns number

        rounded number

        await Canvas(200, 100);
        background(0.8);
        textSize(32);
        text(round(PI, 5), -90, 10);
    save: (data?: object, fileName?: string) => void

    Type Declaration

      • (data?: object, fileName?: string): void
      • 🛠 Saves data to a file.

        If data is not specified, the canvas will be saved.

        If no arguments are provided, the canvas will be saved as an image file named "untitled.png".

        Parameters

        • Optionaldata: object

          canvas, image, or JS object

        • OptionalfileName: string

          filename to save as

        Returns void

        await Canvas(200);
        background(0.8);
        circle(0, 0, 50);

        q5.mousePressed = function () {
        save('circle.png');
        };
        await Canvas(200);
        background(0.8);
        text('save me?', -90, 0);
        textSize(180);
        let bolt = createTextImage('⚡️');

        q5.mousePressed = function () {
        save(bolt, 'bolt.png');
        };
    saveRecording: (fileName: string) => void

    Type Declaration

      • (fileName: string): void
      • 🎞 Saves the current recording as a video file.

        Parameters

        • fileName: string

        Returns void

        q5.draw = function () {
        square(mouseX, jit(100), 10);
        };

        q5.mousePressed = function () {
        if (!recording) record();
        else saveRecording('squares');
        };
    scale: (x: number, y?: number) => void

    Type Declaration

      • (x: number, y?: number): void
      • 🦋 Scales the drawing context.

        If only one input parameter is provided, the drawing context will be scaled uniformly.

        Parameters

        • x: number

          scaling factor along the x-axis

        • Optionaly: number

          scaling factor along the y-axis

        Returns void

        q5.draw = function () {
        background(0.8);

        scale(mouseX / 10);
        circle(0, 0, 20);
        };
    second: () => number

    Type Declaration

      • (): number
      • 🛠 Returns the current second.

        Returns number

        current second

    set: (x: number, y: number, val: any) => void

    Type Declaration

      • (x: number, y: number, val: any): void
      • 🌆 Sets a pixel's color in the image or canvas. Color mode must be RGB.

        Or if a canvas or image is provided, it's drawn on top of the destination image or canvas, ignoring its tint setting.

        Run updatePixels to apply the changes.

        Not applicable to WebGPU canvases.

        Parameters

        • x: number
        • y: number
        • val: any

          color, canvas, or image

        Returns void

        await Canvas(200);
        noSmooth();
        let c = color('lime');
        let img = createImage(50, 50);

        q5.draw = function () {
        img.set(random(50), random(50), c);
        img.updatePixels();
        background(img);
        };
    shadow: (color: string | Color) => void

    Type Declaration

      • (color: string | Color): void
      • 💅 Sets the shadow color. The default is transparent (no shadow).

        Shadows apply to anything drawn to the canvas, including filled shapes, strokes, text, and images.

        Like the color function, this function can accept colors in a wide range of formats: as a CSS color string, a Color object, grayscale value, or color component values.

        Not available in q5 WebGPU.

        Parameters

        • color: string | Color

          shadow color

        Returns void

    shadowBox: (offsetX: number, offsetY: number, blur: number) => void

    Type Declaration

      • (offsetX: number, offsetY: number, blur: number): void
      • 💅 Sets the shadow offset and blur radius.

        When q5 starts, shadow offset is (10, 10) with a blur of 10.

        Not available in q5 WebGPU.

        Parameters

        • offsetX: number

          horizontal offset of the shadow

        • offsetY: number

          vertical offset of the shadow, defaults to be the same as offsetX

        • blur: number

          blur radius of the shadow, defaults to 0

        Returns void

    shearX: (angle: number) => void

    Type Declaration

      • (angle: number): void
      • 🦋 Shears the drawing context along the x-axis.

        Parameters

        • angle: number

          shear angle in radians

        Returns void

        q5.draw = function () {
        background(0.8);

        translate(-75, -40);
        shearX(mouseX / 100);
        square(0, 0, 80);
        };
    shearY: (angle: number) => void

    Type Declaration

      • (angle: number): void
      • 🦋 Shears the drawing context along the y-axis.

        Parameters

        • angle: number

          shear angle in radians

        Returns void

        q5.draw = function () {
        background(0.8);

        translate(-75, -40);
        shearY(mouseX / 100);
        square(0, 0, 80);
        };
    shuffle: (arr: any[]) => any[]

    Type Declaration

      • (arr: any[]): any[]
      • 🛠 Shuffles the elements of an array.

        Parameters

        • arr: any[]

          array to shuffle

        Returns any[]

        shuffled array

    sin: (angle: number) => number
    smooth: () => void

    Type Declaration

      • (): void
      • 🌆 Enables smooth rendering of images displayed larger than their actual size. This is the default setting, so running this function only has an effect if noSmooth has been called.

        Returns void

        await Canvas(200);
        smooth();

        let icon = await load('/q5js_icon.png');
        image(icon, -100, -100, 200, 200);
    sq: (n: number) => number

    Type Declaration

      • (n: number): number
      • 🧮 Calculates the square of a number.

        Parameters

        • n: number

          number to square

        Returns number

        square of the number

    sqrt: (n: number) => number

    Type Declaration

      • (n: number): number
      • 🧮 Calculates the square root of a number.

        Parameters

        • n: number

          a number

        Returns number

        square root of the number

    square: (x: number, y: number, size: number, rounded?: number) => void

    Type Declaration

      • (x: number, y: number, size: number, rounded?: number): void
      • 🧑‍🎨 Draws a square or a rounded square.

        Also accepts 7 parameters to specify a corner radius for each corner, in the order: top-left, top-right, bottom-right, bottom-left.

        Parameters

        • x: number

          x-coordinate

        • y: number

          y-coordinate

        • size: number

          size of the sides of the square

        • Optionalrounded: number

          radius for all corners

        Returns void

        await Canvas(200);
        background(0.8);

        square(-70, -70, 40);
        square(-20, -20, 40, 10);
        square(30, 30, 40, 20, 4, 0, 8);
    storeItem: (key: string, val: string) => void

    Type Declaration

      • (key: string, val: string): void
      • 🛠 Stores an item in localStorage.

        Parameters

        • key: string

          key under which to store the item

        • val: string

          value to store

        Returns void

    stroke: (c0: number, c1: number, c2: number, c3: number) => void

    Type Declaration

      • (c0: number, c1: number, c2: number, c3: number): void
      • 💅 Sets the stroke (outline) color. The default is black.

        Like the color function, this function can accept colors in a wide range of formats: as a CSS color string, a Color object, grayscale value, or color component values.

        Parameters

        • c0: number
        • c1: number
        • c2: number
        • c3: number

        Returns void

        await Canvas(200);
        background(0.8);
        fill(0.14);

        stroke('red');
        circle(-20, -20, 80);

        stroke('lime');
        square(-20, -20, 80);
    strokeCap: (val: CanvasLineCap) => void

    Type Declaration

      • (val: CanvasLineCap): void
      • 💅 Set the line cap style to SQUARE or PROJECT.

        Parameters

        • val: CanvasLineCap

          line cap style

        Returns void

        await Canvas(200);
        background(0.8);
        strokeWeight(20);

        strokeCap(SQUARE);
        line(-50, -25, 50, -25);

        strokeCap(PROJECT);
        line(-50, 25, 50, 25);
    strokeJoin: (val: CanvasLineJoin) => void

    Type Declaration

      • (val: CanvasLineJoin): void
      • 💅 Set the line join style to ROUND or MITER.

        The default is MITER.

        Parameters

        • val: CanvasLineJoin

          line join style

        Returns void

        await Canvas(200);
        background(0.8);
        strokeWeight(10);

        strokeJoin(ROUND);
        triangle(-50, -30, 50, -30, -50, 20);

        strokeJoin(MITER);
        triangle(50, 0, -50, 50, 50, 50);
    strokeWeight: (weight: number) => void

    Type Declaration

      • (weight: number): void
      • 💅 Sets the size of the stroke used for lines and the border around drawings.

        Parameters

        • weight: number

          size of the stroke in pixels

        Returns void

        await Canvas(200);
        background(0.8);
        stroke('red');
        circle(-50, 0, 80);

        strokeWeight(12);
        circle(50, 0, 80);
    tan: (angle: number) => number
    text: (
        str: string,
        x: number,
        y: number,
        wrapWidth?: number,
        lineLimit?: number,
    ) => void

    Type Declaration

      • (
            str: string,
            x: number,
            y: number,
            wrapWidth?: number,
            lineLimit?: number,
        ): void
      • 📘 Renders text on the canvas.

        Parameters

        • str: string

          string of text to display

        • x: number

          x-coordinate of the text's position

        • y: number

          y-coordinate of the text's position

        • OptionalwrapWidth: number

          maximum line width in characters

        • OptionallineLimit: number

          maximum number of lines

        Returns void

        await Canvas(200, 100);
        background('silver');

        textSize(32);
        text('Hello, world!', -88, 10);
        await Canvas(200);
        background(0.8);
        textSize(20);

        let info =
        'q5.js was designed to make creative coding fun and accessible for artists, designers, educators, and beginners.';

        text(info, -88, -70, 20);
        //
        //
    textAlign: (
        horiz: "left" | "center" | "right",
        vert?: "top" | "middle" | "bottom" | "alphabetic",
    ) => void

    Type Declaration

      • (
            horiz: "left" | "center" | "right",
            vert?: "top" | "middle" | "bottom" | "alphabetic",
        ): void
      • 📘 Sets the horizontal and vertical alignment of text.

        Alignment constants like CENTER can be used with this function.

        Parameters

        • horiz: "left" | "center" | "right"

          horizontal alignment

        • Optionalvert: "top" | "middle" | "bottom" | "alphabetic"

          vertical alignment

        Returns void

        await Canvas(200);
        background(0.8);
        textSize(32);

        textAlign(CENTER, CENTER);
        text('Hello, world!', 0, 0);
    textAscent: (str: string) => number

    Type Declaration

      • (str: string): number
      • 📘 Calculates and returns the ascent (the distance from the baseline to the top of the highest character) of the current font.

        Parameters

        • str: string

          string to measure

        Returns number

        ascent of the text in pixels

        q5.draw = function () {
        background(0.8);

        textSize(abs(mouseX));
        rect(-90, 90, textWidth('A'), -textAscent());
        text('A', -90, 90);
        };
    textDescent: (str: string) => number

    Type Declaration

      • (str: string): number
      • 📘 Calculates and returns the descent (the distance from the baseline to the bottom of the lowest character) of the current font.

        Parameters

        • str: string

          string to measure

        Returns number

        descent of the text in pixels

        await Canvas(200);
        background(0.8);
        textSize(64);

        rect(-100, 0, 200, textDescent('q5'));
        text('q5', -90, 0);
    textFont: (fontName: string) => void

    Type Declaration

      • (fontName: string): void
      • 📘 Sets the current font to be used for rendering text.

        By default, the font is set to the CSS font family "sans-serif" or the last font loaded.

        Parameters

        • fontName: string

          name of the font family or a FontFace object

        Returns void

        await Canvas(200, 160);
        background(0.8);

        textFont('serif');

        text('Hello, world!', -96, 10);
        await Canvas(200);
        background(0.8);

        textFont('monospace');

        text('Hello, world!', -96, 10);
    textImage: (img: String | Image, x: number, y: number) => void

    Type Declaration

      • (img: String | Image, x: number, y: number): void
      • 📘 Renders an image generated from text onto the canvas.

        If the first parameter is a string, an image of the text will be created and cached automatically.

        The positioning of the image is affected by the current text alignment and baseline settings.

        This function can be used to draw emojis, which can not be drawn with MSDF text rendering.

        Using this function to draw text that changes every frame has a very high performance cost.

        Parameters

        • img: String | Image

          image or text

        • x: number

          x-coordinate where the image should be placed

        • y: number

          y-coordinate where the image should be placed

        Returns void

        await Canvas(200);
        background(0.8);
        textSize(96);
        textAlign(CENTER, CENTER);

        textImage('🐶', 0, 0);
    textLeading: (leading?: number) => number | void

    Type Declaration

      • (leading?: number): number | void
      • 📘 Sets or gets the current line height. If no argument is provided, returns the current line height.

        Parameters

        • Optionalleading: number

          line height in pixels

        Returns number | void

        current line height when no argument is provided

        q5.draw = function () {
        background(0.8);

        textSize(abs(mouseX));
        text('A', -90, 90);
        rect(-90, 90, 5, -textLeading());
        };
    textSize: (size?: number) => number | void

    Type Declaration

      • (size?: number): number | void
      • 📘 Sets or gets the current font size. If no argument is provided, returns the current font size.

        Parameters

        • Optionalsize: number

          size of the font in pixels

        Returns number | void

        current font size when no argument is provided

        q5.draw = function () {
        background(0.8);

        textSize(abs(mouseX));
        text('A', -90, 90);
        };
    textStyle: (style: "normal" | "italic" | "bold" | "bolditalic") => void

    Type Declaration

      • (style: "normal" | "italic" | "bold" | "bolditalic"): void
      • 📘 Sets the current text style.

        Not applicable to MSDF fonts.

        Parameters

        • style: "normal" | "italic" | "bold" | "bolditalic"

          font style

        Returns void

        await Canvas(200);
        background(0.8);

        textStyle(ITALIC);

        textSize(32);
        text('Hello, world!', -88, 6);
    textToPoints: (
        str: string,
        x?: number,
        y?: number,
        sampleRate?: number,
        density?: number,
    ) => []

    Type Declaration

      • (str: string, x?: number, y?: number, sampleRate?: number, density?: number): []
      • 📘 Converts a string of text to an array of points.

        Samples opaque pixels in a text image made with createTextImage.

        It's influenced by text settings, such as font, size, and alignment.

        Uses a Z-order curve to improve spatial distribution, which preserves the shape of text better than purely random sampling.

        Parameters

        • str: string

          string of text

        • Optionalx: number

          x coordinate of the text position

        • Optionaly: number

          y coordinate of the text position

        • OptionalsampleRate: number

          lower values increase dithering (1 = all points, 0.1 = ~10% of points)

        • Optionaldensity: number

          pixel density of the text

        Returns []

        await Canvas(200);
        textSize(220);
        textAlign(CENTER, CENTER);

        let points = textToPoints('5');

        for (let pt of points) {
        rect(pt.x, pt.y, 5, 20);
        }
        await Canvas(200, 296);
        textSize(340);
        noFill();
        stroke(1);
        strokeWeight(8);

        let pts = textToPoints('q', -100, 56);

        strokeWeight(1);
        for (let pt of pts) {
        ellipse(pt.x, pt.y, 10, 0.1);
        }
    textWeight: (weight: string | number) => void

    Type Declaration

      • (weight: string | number): void
      • 📘 Sets the text weight.

        • 100: thin
        • 200: extra-light
        • 300: light
        • 400: normal/regular
        • 500: medium
        • 600: semi-bold
        • 700: bold
        • 800: bolder/extra-bold
        • 900: black/heavy

        Parameters

        • weight: string | number

          font weight

        Returns void

        await Canvas(200);
        background(0.8);
        textSize(32);
        textAlign(CENTER, CENTER);

        textWeight(100);
        text('Hello, world!', 0, 0);
    textWidth: (str: string) => number

    Type Declaration

      • (str: string): number
      • 📘 Calculates and returns the width of a given string of text.

        Parameters

        • str: string

          string to measure

        Returns number

        width of the text in pixels

        q5.draw = function () {
        background(0.8);

        textSize(abs(mouseX));
        rect(-90, 90, textWidth('A'), -textLeading());
        text('A', -90, 90);
        };
    tint: (color: string | number) => void

    Type Declaration

      • (color: string | number): void
      • 🌆 Applies a tint (color overlay) to the drawing.

        The alpha value of the tint color determines the strength of the tint. To change an image's opacity, use the opacity function.

        Tinting affects all subsequent images drawn. The tint color is applied to images using the "multiply" blend mode.

        Since the tinting process is performance intensive, each time an image is tinted, q5 caches the result. image will draw the cached tinted image unless the tint color has changed or the image being tinted was edited.

        If you need to draw an image multiple times each frame with different tints, consider making copies of the image and tinting each copy separately.

        Parameters

        • color: string | number

          tint color

        Returns void

        await Canvas(200);

        let logo = await load('/q5js_logo.avif');

        tint(1, 0, 0, 0.5);
        image(logo, -100, -100, 200, 200);
    touchEnded: () => void

    Type Declaration

      • (): void
      • 🖲 Define this function to respond to touch down events on the canvas.

        Return true to enable touch gestures like pinch-to-zoom and scroll, which q5 disables on the canvas by default.

        Returns void

        await Canvas(200);
        let gray = 0.4;

        q5.touchEnded = function () {
        background(gray % 1);
        gray += 0.1;
        };
    touchMoved: () => void

    Type Declaration

      • (): void
      • 🖲 Define this function to respond to touch move events on the canvas.

        Return true to enable touch gestures like pinch-to-zoom and scroll, which q5 disables on the canvas by default.

        Returns void

        await Canvas(200);
        let gray = 0.4;

        q5.touchMoved = function () {
        background(gray % 1);
        gray += 0.005;
        };
    touchStarted: () => void

    Type Declaration

      • (): void
      • 🖲 Define this function to respond to touch down events on the canvas.

        Return true to enable touch gestures like pinch-to-zoom and scroll, which q5 disables on the canvas by default.

        Returns void

        await Canvas(200);
        let gray = 0.4;

        q5.touchStarted = function () {
        background(gray % 1);
        gray += 0.1;
        };
    translate: (x: number, y: number) => void

    Type Declaration

      • (x: number, y: number): void
      • 🦋 Translates the origin of the drawing context.

        Parameters

        • x: number

          translation along the x-axis

        • y: number

          translation along the y-axis

        Returns void

        q5.draw = function () {
        background(0.8);

        translate(50, 50);
        circle(0, 0, 80);
        };
    trim: () => Image

    Type Declaration

      • (): Image
      • 🌆 Returns a trimmed image, cropping out transparent pixels from the edges.

        Returns Image

    updatePixels: () => void

    Type Declaration

      • (): void
      • 🌆 Applies changes in the pixels array to the canvas or image.

        Not applicable to WebGPU canvases.

        Returns void

        await Canvas(200);
        let c = color('pink');

        let img = createImage(50, 50);
        for (let x = 0; x < 50; x += 3) {
        for (let y = 0; y < 50; y += 3) {
        img.set(x, y, c);
        }
        }
        img.updatePixels();

        background(img);
    userStartAudio: () => Promise<void>

    Type Declaration

      • (): Promise<void>
      • 🔊 Creates a new AudioContext or resumes it if it was suspended.

        Returns Promise<void>

        a promise that resolves when the AudioContext is resumed

    year: () => number

    Type Declaration

      • (): number
      • 🛠 Returns the current year.

        Returns number

        current year

    canvasOptions: object

    ⚙ Sets the default canvas context attributes used for newly created canvases and internal graphics. These options are overwritten by any per-canvas options you pass to Canvas.

    disableFriendlyErrors: boolean

    ⚙ Turn off q5's friendly error messages.

    errorTolerant: boolean

    ⚙ Set to true to keep draw looping after an error.

    lang: string

    ⚙ Set to a language code other than 'en' (English) to use q5 in an additional language.

    Currently supported languages:

    • 'es' (Spanish)
    MAX_CHARS: number

    ⚙ A WebGPU memory allocation limit.

    The maximum number of text characters that can be drawn per frame.

    MAX_ELLIPSES: number

    ⚙ A WebGPU memory allocation limit.

    The maximum number of ellipses (calls to ellipse, circle, and arc) that can be drawn per frame.

    MAX_RECTS: number

    ⚙ A WebGPU memory allocation limit.

    The maximum number of rectangles (calls to rect, square, capsule) that can be drawn per frame.

    MAX_TEXTS: number

    ⚙ A WebGPU memory allocation limit.

    The maximum number of separate calls to text that can be drawn per frame.

    MAX_TRANSFORMS: number

    ⚙ A WebGPU memory allocation limit.

    The maximum number of transformation matrixes that can be used per frame.

    modules: object

    ⚙ An object containing q5's modules, functions that run when q5 loads.

    Each function receives two input parameters:

    • the q5 instance
    • a proxy for editing the q5 instance and corresponding properties of the global scope
    supportsHDR: boolean

    ⚙ True if the device supports HDR (the display-p3 colorspace).

    version: string

    ⚙ The current minor version of q5.

    the q5 version

    await Canvas(200);
    background(0.8);
    textSize(64);
    textAlign(CENTER, CENTER);
    text('v' + Q5.version, 0, 0);

    Methods

    • Returns void

    • Returns void

    • Returns void

    • ⚙ Addons can augment q5 with new functionality by adding hooks, functions to be run at specific phases in the q5 lifecycle.

      Inside the function, this refers to the Q5 instance.

      Parameters

      • lifecycle: string

        'init', 'presetup', 'postsetup', 'predraw', 'postdraw', or 'remove'

      • fn: Function

        The function to be run at the specified lifecycle phase.

      Returns void

    • ⚙ The q5 draw function is run 60 times per second by default.

      Returns void

    • ⚙ Runs after each draw function call and post-draw q5 addon processes, if any.

      Useful for adding post-processing effects when it's not possible to do so at the end of the draw function, such as when using addons like q5play that auto-draw to the canvas after the draw function is run.

      Returns void

    • ⚙ p5.js v2 compatible way to register an addon with q5.

      Parameters

      • addon: Function

        A function that receives Q5, Q5.prototype, and a lifecycles object.

      Returns void

    • Returns void

    • ⚙ Creates a new Q5 instance that uses q5's WebGPU renderer.

      Returns Q5

      let q = await Q5.WebGPU('namespace');
      q.Canvas(200, 100);

      q.draw = () => {
      q.background(0.8);
      q.circle(q.mouseX, 0, 80);
      };