hammerspoon2-docs
    Preparing search index...

    Class HSCanvas

    HSCanvas

    A single canvas window: an absolutely-positioned, low-level drawing surface mirroring v1 Hammerspoon's hs.canvas. Elements are plain JS objects (matching v1's Lua tables) added with appendElements() and mutated in place with setElementAttribute()/elementAttribute(). Supports the same fill/stroke/ strokeAndFill/clip/build/skip action pipeline as v1, including the build+clip+reversePath technique used to punch holes in shapes (see hs.canvas.windowLevels/hs.canvas.windowBehaviors for the window-level/Spaces controls needed alongside this for overlay-style canvases).

    const c = hs.canvas.create({x: 100, y: 100, w: 200, h: 200})
    c.appendElements([
    { type: "rectangle", action: "fill", fillColor: { red: 0.2, green: 0.5, blue: 0.9, alpha: 1 } }
    ])
    c.show()
    Index

    Constructors

    Methods

    • The opacity of the canvas window

      Returns number

      The opacity, from 0 (fully transparent) to 1 (fully opaque)

    • Append one or more elements to the end of the canvas Element frame/center/coordinates values are y-down (y = 0 at the top of the canvas) -- a different sense from the canvas window's own x/y position, which is unflipped AppKit screen coordinates. See hs.canvas's module-level docs for the full explanation.

      Parameters

      • elements: object[]

        Array of element dictionaries (each needs at least a type)

      Returns HSCanvas

      Self for chaining

      Throws an Error on failure; wrap calls in try/catch to handle it.

    • Replace the element at an index, or append if the index equals the current element count

      Parameters

      • element: Record<string, any>

        The replacement element dictionary

      • index: number

        The index to replace

      Returns HSCanvas

      Self for chaining

      Throws an Error on failure; wrap calls in try/catch to handle it.

    • Set the window's Spaces/Exposé collection behavior to a single named behavior

      Parameters

      • name: string

        A behavior name from hs.canvas.windowBehaviors (e.g. "canJoinAllSpaces")

      Returns HSCanvas

      Self for chaining

    • Set the window's Spaces/Exposé collection behavior to a combination of named behaviors

      Parameters

      • names: string[]

        Behavior names from hs.canvas.windowBehaviors, combined together

      Returns HSCanvas

      Self for chaining

    • Set the window's Spaces/Exposé collection behavior to a raw bitmask

      Parameters

      • value: number

        A raw NSWindow.CollectionBehavior bitmask

      Returns HSCanvas

      Self for chaining

    • All elements currently on the canvas

      Returns object[]

      Array of element dictionaries

    • Enable whole-canvas mouse tracking for regions not covered by any individually tracked element. Delivered through mouseCallback() with id "_canvas". all six flags, so omitting this turns right mouse-down tracking off six flags, so omitting this turns right mouse-up tracking off

      Parameters

      • down: boolean

        Track mouse-down events

      • up: boolean

        Track mouse-up events

      • enterExit: boolean

        Track mouse enter/exit events

      • move: boolean

        Track mouse-move events

      • OptionalrightDown: boolean

        Track right mouse-down events (defaults to false). Every call sets

      • OptionalrightUp: boolean

        Track right mouse-up events (defaults to false). Every call sets all

      Returns HSCanvas

      Self for chaining

    • Remove the whole-canvas transformation set by setTransformation()

      Returns HSCanvas

      Self for chaining

    • Set whether clicking the canvas activates the Hammerspoon app

      Parameters

      • flag: boolean

        Pass false to prevent clicks on the canvas from bringing the app forward

      Returns HSCanvas

      Self for chaining

    • Destroy the canvas window and release its resources, optionally fading it out first This releases the canvas's window, callbacks and elements (including any images they hold) straight away, rather than when the canvas is garbage collected. A destroyed canvas is finished with: from the moment destroy() is called, calling show(), appendElements(), insertElement(), assignElement(), replaceElements(), mouseCallback(), draggingCallback() or duplicate() on it throws an error, and imageFromCanvas() returns null. Named destroy() rather than v1's delete() -- delete cannot be used as a JavaScriptCore-exported method name in this codebase's bridging layer.

      Parameters

      • OptionalfadeOutTime: number

        The number of seconds to fade the canvas out over before destroying it. Defaults to 0, which destroys it immediately

      Returns void

    • Set a callback fired when files or text are dropped onto the canvas

      Parameters

      • callback: (paths: string[]) => void

        Called with the dropped file paths, or a single-element array containing dropped text

      Returns HSCanvas

      Self for chaining

      Throws an Error on failure; wrap calls in try/catch to handle it.

    • Create an independent copy of this canvas, with the same frame, elements, and window configuration Named duplicate() rather than v1's copy() -- this codebase's conventions forbid method names starting with copy (an ARC/ObjC hazard), the same rule that renamed new() to create().

      Returns HSCanvas

      A new HSCanvas

      Throws an Error on failure; wrap calls in try/catch to handle it.

    • Get a single attribute value from an element Returns Any? (mirroring hs.userdefaults.get()) rather than a concrete Swift type because an element attribute's value is genuinely heterogeneous -- a string, number, boolean, nested object, or array, matching v1's dynamically-typed Lua table values.

      Parameters

      • index: number

        The element index

      • key: string

        The attribute key

      Returns any

      The attribute's current value, or null if not set

    • The smallest rectangle enclosing an element's rendered shape

      Parameters

      • index: number

        The element index

      Returns object

      A {x, y, w, h} dictionary

    • The number of elements on the canvas

      Returns number

      The current element count

    • The attribute keys present on an element

      Parameters

      • index: number

        The element index

      Returns string[]

      Array of attribute key names

    • The canvas window's current position and size

      Returns object

      A {x, y, w, h} dictionary, in the same unflipped AppKit screen coordinates as create()

    • Hide the canvas window, optionally fading it out (elements and window config are preserved while you keep a reference to it) The canvas keeps its callbacks, and isShowing() stays true, until a fade-out has finished. Afterwards its alpha() is unchanged, so the next show() brings it back at the same opacity. Hiding a canvas that has been destroyed does nothing.

      Parameters

      • OptionalfadeOutTime: number

        The number of seconds to fade the canvas out over. Defaults to 0, which hides it immediately

      Returns HSCanvas

      Self for chaining

    • Set whether the canvas window ignores all mouse events, passing clicks through to whatever is behind it This is a capability beyond v1's hs.canvas API surface (not a literal v1 method name) -- v1 has no direct equivalent for full click pass-through.

      Parameters

      • flag: boolean

        Pass true to make the canvas fully click-through

      Returns HSCanvas

      Self for chaining

    • Render the canvas's current contents to an image

      Returns HSImage | null

      An HSImage snapshot of the canvas, or null if it could not be rendered or the canvas has been destroyed

    • Insert an element at a specific index

      Parameters

      • element: Record<string, any>

        The element dictionary to insert

      • index: number

        The index to insert at (clamped to the valid range)

      Returns HSCanvas

      Self for chaining

      Throws an Error on failure; wrap calls in try/catch to handle it.

    • Whether the canvas is hidden behind other windows, or off-screen entirely

      Returns boolean

      true if the canvas is showing but fully occluded or off-screen

    • Whether the canvas window is currently ordered onto the screen

      Returns boolean

      true if the canvas has been shown and not hidden or destroyed

    • Whether the canvas is showing AND at least partially visible (not fully occluded or off-screen)

      Returns boolean

      true if the canvas is showing and at least partially on-screen

    • Set the window level by name

      Parameters

      • name: string

        A level name from hs.canvas.windowLevels (e.g. "floating", "screenSaver")

      Returns HSCanvas

      Self for chaining

    • Set the window level to a raw numeric value Split out from level(_:) (rather than accepting a string-or-number union) because JSExport parameters must have a single concrete type -- see hs.canvas.windowLevels, which exposes raw numeric values (not opaque name strings) so scripts can do arithmetic on them, matching v1 behavior.

      Parameters

      • value: number

        A raw numeric window level

      Returns HSCanvas

      Self for chaining

    • The smallest size that can fully render a string of text, using the font attributes (textFont/textSize/textWeight/textDesign/textItalic) of an element, of an attributes object, or the defaults index. Any element type works; attributes it doesn't set use their defaults. object, so text can be measured before any element exists. at size 27, as a text element with no font attributes would be drawn). Multi-line strings (separated by \n) are measured correctly -- the height covers every line and the width is the longest line's width, not a fixed single-line size.

      Parameters

      • source:
            | string
            | number
            | {
                textDesign?: string;
                textFont?: string;
                textItalic?: boolean;
                textSize?: number;
                textWeight?: string;
            }

        The index of an element whose font attributes to measure with, an object of font attributes, or the string to measure (to use the default font attributes)

      • Optionaltext: string

        The string to measure -- it doesn't need to match the element's own text. Omitted when source is the string

      Returns object

      A {w, h} dictionary, or {} (with a warning logged) if index is out of bounds or the arguments are invalid

    • Set the callback fired for tracked mouse events Fires for elements with trackMouseDown/trackMouseUp/trackMouseEnterExit/ trackMouseMove/trackRightMouseDown/trackRightMouseUp set to true in their element dictionary, and for whole-canvas regions enabled via canvasMouseEvents() (delivered with id "_canvas"). mouseDown/mouseUp are the left button only; the right button (or a Ctrl-click, the standard macOS secondary click) is reported separately as rightMouseDown/rightMouseUp.

      Parameters

      • callback: (canvas: HSCanvas, message: string, id: any, x: number, y: number) => void

        A JavaScript function called with the canvas, the event name ("mouseDown"/"mouseUp"/"rightMouseDown"/"rightMouseUp"/"mouseEnter"/"mouseExit"/"mouseMove"), the tracked element's id, and the event's x/y coordinates

      Returns HSCanvas

      Self for chaining

      Throws an Error on failure; wrap calls in try/catch to handle it.

    • Remove the element at a specific index

      Parameters

      • index: number

        The index to remove

      Returns HSCanvas

      Self for chaining

    • Remove a single attribute from an element

      Parameters

      • index: number

        The element index

      • key: string

        The attribute key to remove

      Returns HSCanvas

      Self for chaining

    • Remove the last element

      Returns HSCanvas

      Self for chaining

    • Replace all elements on the canvas

      Parameters

      • elements: object[]

        The new full element list

      Returns HSCanvas

      Self for chaining

      Throws an Error on failure; wrap calls in try/catch to handle it.

    • Rotate an element about its own bounding-box center

      Parameters

      • index: number

        The element index

      • angle: number

        The rotation angle, in degrees

      Returns HSCanvas

      Self for chaining

    • Rotate an element about a specific point

      Parameters

      • index: number

        The element index

      • angle: number

        The rotation angle, in degrees

      • point: object

        A {x, y} dictionary giving the pivot point

      Returns HSCanvas

      Self for chaining

    • Set the accessibility subrole reported for this canvas's window

      Parameters

      • subrole: string

        The accessibility subrole string

      Returns HSCanvas

      Self for chaining

    • Set the opacity of the whole canvas window This is the opacity show() fades in to, and that a hidden canvas comes back at.

      Parameters

      • alpha: number

        The opacity, from 0 (fully transparent) to 1 (fully opaque). Values outside that range are clamped

      Returns HSCanvas

      Self for chaining

    • Set a single attribute value on an element

      Parameters

      • index: number

        The element index

      • key: string

        The attribute key

      • value: any

        The value to assign

      Returns HSCanvas

      Self for chaining

    • Apply a raw 2D affine transformation matrix to a single element

      Parameters

      • index: number

        The element index

      • matrix: object

        A {m11, m12, m21, m22, tX, tY} matrix dictionary

      Returns HSCanvas

      Self for chaining

    • Move and/or resize the canvas window

      Parameters

      • rect: object

        A {x, y, w, h} dictionary. Any keys left out keep their current value

      Returns HSCanvas

      Self for chaining

    • Resize the canvas window without moving its top-left corner

      Parameters

      • dimensions: object

        A {w, h} dictionary. Any keys left out keep their current value

      Returns HSCanvas

      Self for chaining

    • Move the canvas window without changing its size

      Parameters

      • point: object

        An {x, y} dictionary giving the new top-left corner. Any keys left out keep their current value

      Returns HSCanvas

      Self for chaining

    • Apply a raw 2D affine transformation matrix to the whole canvas

      Parameters

      • matrix: object

        A {m11, m12, m21, m22, tX, tY} matrix dictionary

      Returns HSCanvas

      Self for chaining

    • Show the canvas window, optionally fading it in A fade goes from fully transparent up to the canvas's alpha(). Calling show(), hide() or destroy() while a fade is running replaces that fade, so showing a canvas that is fading out of hide() brings it back. A canvas that has been destroyed can't be shown again, even while it is still fading out.

      Parameters

      • OptionalfadeInTime: number

        The number of seconds to fade the canvas in over. Defaults to 0, which shows it immediately

      Returns HSCanvas

      Self for chaining

      A shown canvas stays on screen, with its callbacks, until it's hidden or destroyed, even if you don't keep a reference to it

      Throws an Error on failure; wrap calls in try/catch to handle it.

    • The canvas window's current size

      Returns object

      A {w, h} dictionary

    • The canvas window's current top-left corner the point at the window's highest y (its screen-visual top), not y = 0.

      Returns object

      An {x, y} dictionary