API Docs

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).

Example

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()

Properties

This type has no properties.

Methods

show(fadeInTime) -> HSCanvas

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.

show(fadeInTime) -> HSCanvas
Name Type Description
fadeInTime optional number The number of seconds to fade the canvas in over. Defaults to 0, which shows it immediately
Self for chaining
Throws an Error on failure; wrap calls in try/catch to handle it.
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
c.show(0.3)

hide(fadeOutTime) -> HSCanvas

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.

hide(fadeOutTime) -> HSCanvas
Name Type Description
fadeOutTime optional number The number of seconds to fade the canvas out over. Defaults to 0, which hides it immediately
Self for chaining
c.hide(0.3)

destroy(fadeOutTime) -> None

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.

destroy(fadeOutTime) -> None
Name Type Description
fadeOutTime optional number The number of seconds to fade the canvas out over before destroying it. Defaults to 0, which destroys it immediately
None
c.destroy(0.3)

alpha() -> number

The opacity of the canvas window

alpha() -> number
number
The opacity, from 0 (fully transparent) to 1 (fully opaque)

setAlpha(alpha) -> HSCanvas

Set the opacity of the whole canvas window

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

setAlpha(alpha) -> HSCanvas
Name Type Description
alpha number The opacity, from 0 (fully transparent) to 1 (fully opaque). Values outside that range are clamped
Self for chaining
c.setAlpha(0.5)

isShowing() -> boolean

Whether the canvas window is currently ordered onto the screen

isShowing() -> boolean
boolean
true if the canvas has been shown and not hidden or destroyed

isVisible() -> boolean

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

isVisible() -> boolean
boolean
true if the canvas is showing and at least partially on-screen

isOccluded() -> boolean

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

isOccluded() -> boolean
boolean
true if the canvas is showing but fully occluded or off-screen

frame() -> object

The canvas window's current position and size

frame() -> {x: number, y: number, w: number, h: number}
object
A {x, y, w, h} dictionary, in the same screen coordinates as create() and hs.screen (y = 0 at the top of the primary screen)
Field Type Description
x number
y number
w number
h number

setFrame(rect) -> HSCanvas

Move and/or resize the canvas window

setFrame(rect) -> HSCanvas
Name Type Description
rect HSRect | {x?: number, y?: number, w?: number, h?: number} An HSRect (e.g. a window's or screen's frame) or a {x, y, w, h} dictionary, in the same screen coordinates as hs.screen and hs.window. Any keys left out of a dictionary keep their current value
Self for chaining
c.setFrame({x: 200, y: 200, w: 300, h: 300})
c.setFrame(hs.window.focusedWindow().frame)

topLeft() -> object

The canvas window's current top-left corner

This is the same point as frame()'s x/y.

topLeft() -> {x: number, y: number}
object
An {x, y} dictionary
Field Type Description
x number
y number

setTopLeft(point) -> HSCanvas

Move the canvas window without changing its size

setTopLeft(point) -> HSCanvas
Name Type Description
point HSPoint | {x?: number, y?: number} An HSPoint or an {x, y} dictionary giving the new top-left corner. Any keys left out of a dictionary keep their current value
Self for chaining
c.setTopLeft({x: 200, y: 100})

size() -> object

The canvas window's current size

size() -> {w: number, h: number}
object
A {w, h} dictionary
Field Type Description
w number
h number

setSize(dimensions) -> HSCanvas

Resize the canvas window without moving its top-left corner

setSize(dimensions) -> HSCanvas
Name Type Description
dimensions object A {w, h} dictionary. Any keys left out keep their current value
w optional number
h optional number
Self for chaining
c.setSize({w: 400, h: 300})

level(name) -> HSCanvas

Set the window level by name

level(name) -> HSCanvas
Name Type Description
name string A level name from hs.canvas.windowLevels (e.g. "floating", "screenSaver")
Self for chaining
c.level("floating")

levelValue(value) -> HSCanvas

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.

levelValue(value) -> HSCanvas
Name Type Description
value number A raw numeric window level
Self for chaining
c.levelValue(hs.canvas.windowLevels.screenSaver + 1)

behavior(name) -> HSCanvas

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

behavior(name) -> HSCanvas
Name Type Description
name string A behavior name from hs.canvas.windowBehaviors (e.g. "canJoinAllSpaces")
Self for chaining
c.behavior("canJoinAllSpaces")

behaviorList(names) -> HSCanvas

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

Throws if the behavior combines flags AppKit treats as mutually exclusive (e.g. canJoinAllSpaces with moveToActiveSpace), leaving the current behavior unchanged. Unknown names are logged and ignored.

behaviorList(names) -> HSCanvas
Name Type Description
names string[] Behavior names from hs.canvas.windowBehaviors, combined together
Self for chaining
Throws an Error on failure; wrap calls in try/catch to handle it.
c.behaviorList(["canJoinAllSpaces", "stationary"])

behaviorValue(value) -> HSCanvas

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

Throws if the behavior combines flags AppKit treats as mutually exclusive (e.g. canJoinAllSpaces with moveToActiveSpace), leaving the current behavior unchanged.

behaviorValue(value) -> HSCanvas
Name Type Description
value number A raw NSWindow.CollectionBehavior bitmask
Self for chaining
Throws an Error on failure; wrap calls in try/catch to handle it.
c.behaviorValue(hs.canvas.windowBehaviors.canJoinAllSpaces | hs.canvas.windowBehaviors.stationary)

clickActivating(flag) -> HSCanvas

Set whether clicking the canvas activates the Hammerspoon app

A canvas that isn't click-activating is also the only kind that can appear over another application's fullscreen window while Hammerspoon shows a Dock icon. Without a Dock icon, any canvas can, as long as its behavior() lets it join that Space (e.g. canJoinAllSpaces).

clickActivating(flag) -> HSCanvas
Name Type Description
flag boolean Pass false to prevent clicks on the canvas from bringing the app forward
Self for chaining
// An overlay that also shows over fullscreen applications
c.clickActivating(false).behavior("canJoinAllSpaces").level("screenSaver").show()

ignoreMouseEvents(flag) -> HSCanvas

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.

ignoreMouseEvents(flag) -> HSCanvas
Name Type Description
flag boolean Pass true to make the canvas fully click-through
Self for chaining

appendElements(elements) -> HSCanvas

Append one or more elements to the end of the canvas

Element frame/center/coordinates values are relative to the canvas itself: {x: 0, y: 0} is the canvas's top-left corner, and y increases downward.

appendElements(elements) -> HSCanvas
Name Type Description
elements HSCanvasElement[] The elements to add
Self for chaining
Throws an Error on failure; wrap calls in try/catch to handle it.
c.appendElements([{ type: "circle", action: "fill", fillColor: { alpha: 1 } }])

insertElement(element, index) -> HSCanvas

Insert an element at a specific index

insertElement(element, index) -> HSCanvas
Name Type Description
element HSCanvasElement The element to insert
index number The index to insert at (clamped to the valid range)
Self for chaining
Throws an Error on failure; wrap calls in try/catch to handle it.

assignElement(element, index) -> HSCanvas

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

assignElement(element, index) -> HSCanvas
Name Type Description
element HSCanvasElement The replacement element
index number The index to replace
Self for chaining
Throws an Error on failure; wrap calls in try/catch to handle it.

removeElement(index) -> HSCanvas

Remove the element at a specific index

removeElement(index) -> HSCanvas
Name Type Description
index number The index to remove
Self for chaining

removeLastElement() -> HSCanvas

Remove the last element

removeLastElement() -> HSCanvas
Self for chaining

replaceElements(elements) -> HSCanvas

Replace all elements on the canvas

replaceElements(elements) -> HSCanvas
Name Type Description
elements HSCanvasElement[] The new full element list
Self for chaining
Throws an Error on failure; wrap calls in try/catch to handle it.

elementCount() -> number

The number of elements on the canvas

elementCount() -> number
number
The current element count

canvasElements() -> HSCanvasElement[]

All elements currently on the canvas

canvasElements() -> HSCanvasElement[]
The canvas's elements

elementKeys(index) -> string[]

The attribute keys present on an element

elementKeys(index) -> string[]
Name Type Description
index number The element index
string[]
Array of attribute key names

elementAttribute(index, key) -> any

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.

elementAttribute(index, key) -> any
Name Type Description
index number The element index
key string The attribute key
any
The attribute's current value, or null if not set

setElementAttribute(index, key, value) -> HSCanvas

Set a single attribute value on an element

setElementAttribute(index, key, value) -> HSCanvas
Name Type Description
index number The element index
key string The attribute key
value any The value to assign
Self for chaining

removeElementAttribute(index, key) -> HSCanvas

Remove a single attribute from an element

removeElementAttribute(index, key) -> HSCanvas
Name Type Description
index number The element index
key string The attribute key to remove
Self for chaining

elementBounds(index) -> object

The smallest rectangle enclosing an element's rendered shape

elementBounds(index) -> {x: number, y: number, w: number, h: number}
Name Type Description
index number The element index
object
A {x, y, w, h} dictionary
Field Type Description
x number
y number
w number
h number

minimumTextSize(source, text) -> {w: number, h: number} | {}

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

Mirrors v1's hs.canvas:minimumTextSize([index], text). It can be called three ways:

  • minimumTextSize(index, text) measures with the font attributes of the element at index. Any element type works; attributes it doesn't set use their defaults.
  • minimumTextSize(attributes, text) measures with the font attributes in a plain object, so text can be measured before any element exists.
  • minimumTextSize(text) measures with the default font attributes (the system font 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.

minimumTextSize(source, text) -> {w: number, h: number} | {}
Name Type Description
source number | {textFont?: string, textSize?: number, textWeight?: string, textDesign?: string, textItalic?: boolean} | 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)
text optional string The string to measure -- it doesn't need to match the element's own text. Omitted when source is the string
{w: number, h: number} | {}
A {w, h} dictionary, or {} (with a warning logged) if index is out of bounds or the arguments are invalid
// Size a text element to fit its text, before it's added to the canvas
const attributes = { textFont: "Menlo-Bold", textSize: 24 }
const size = c.minimumTextSize(attributes, "Hello\nWorld")
c.appendElements([{ type: "text", text: "Hello\nWorld", ...attributes,
                    frame: { x: 10, y: 10, w: size.w, h: size.h } }])

// Or measure with an existing element's font, or the default font
const fromElement = c.minimumTextSize(0, "Goodbye")
const withDefaults = c.minimumTextSize("Goodbye")

mouseCallback(callback) -> HSCanvas

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.

mouseCallback(callback) -> HSCanvas
Name Type Description
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
Self for chaining
Throws an Error on failure; wrap calls in try/catch to handle it.
c.appendElements([{ type: "circle", action: "fill", trackMouseDown: true, id: "dot" }])
c.mouseCallback((canvas, message, id, x, y) => console.log(message, id, x, y))

// Offer a secondary action on right-click
c.appendElements([{ type: "rectangle", action: "fill", id: "button",
                    trackMouseUp: true, trackRightMouseDown: true }])
c.mouseCallback((canvas, message, id) => {
    if (message === "rightMouseDown") console.log("context menu for", id)
})

canvasMouseEvents(down, up, enterExit, move, rightDown, rightUp) -> HSCanvas

Enable whole-canvas mouse tracking for regions not covered by any individually tracked element. Delivered through mouseCallback() with id "_canvas".

canvasMouseEvents(down, up, enterExit, move, rightDown, rightUp) -> HSCanvas
Name Type Description
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
rightDown optional boolean Track right mouse-down events (defaults to false). Every call sets all six flags, so omitting this turns right mouse-down tracking off
rightUp optional boolean Track right mouse-up events (defaults to false). Every call sets all six flags, so omitting this turns right mouse-up tracking off
Self for chaining
// Left and right clicks anywhere on the canvas
c.canvasMouseEvents(true, false, false, false, true, false)

rotateElement(index, angle) -> HSCanvas

Rotate an element about its own bounding-box center

rotateElement(index, angle) -> HSCanvas
Name Type Description
index number The element index
angle number The rotation angle, in degrees
Self for chaining

rotateElementAroundPoint(index, angle, point) -> HSCanvas

Rotate an element about a specific point

rotateElementAroundPoint(index, angle, point) -> HSCanvas
Name Type Description
index number The element index
angle number The rotation angle, in degrees
point object A {x, y} dictionary giving the pivot point
x optional number | string
y optional number | string
Self for chaining

setElementTransformation(index, matrix) -> HSCanvas

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

setElementTransformation(index, matrix) -> HSCanvas
Name Type Description
index number The element index
matrix object A {m11, m12, m21, m22, tX, tY} matrix dictionary
m11 optional number
m12 optional number
m21 optional number
m22 optional number
tX optional number
tY optional number
Self for chaining

setTransformation(matrix) -> HSCanvas

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

setTransformation(matrix) -> HSCanvas
Name Type Description
matrix object A {m11, m12, m21, m22, tX, tY} matrix dictionary
m11 optional number
m12 optional number
m21 optional number
m22 optional number
tX optional number
tY optional number
Self for chaining

clearTransformation() -> HSCanvas

Remove the whole-canvas transformation set by setTransformation()

clearTransformation() -> HSCanvas
Self for chaining

imageFromCanvas() -> HSImage

Render the canvas's current contents to an image

imageFromCanvas() -> HSImage
An HSImage snapshot of the canvas, or null if it could not be rendered or the canvas has been destroyed

duplicate() -> HSCanvas

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().

duplicate() -> HSCanvas
A new HSCanvas
Throws an Error on failure; wrap calls in try/catch to handle it.

setAccessibilitySubrole(subrole) -> HSCanvas

Set the accessibility subrole reported for this canvas's window

By default a canvas reports AppKit's subrole for it with .Hammerspoon appended (e.g. AXUnknown.Hammerspoon), so window managers don't treat it as an ordinary window.

setAccessibilitySubrole(subrole) -> HSCanvas
Name Type Description
subrole string The accessibility subrole string, or "" to go back to the default
Self for chaining
c.setAccessibilitySubrole("MyOverlay")

draggingCallback(callback) -> HSCanvas

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

draggingCallback(callback) -> HSCanvas
Name Type Description
callback (paths: string[]) => void Called with the dropped file paths, or a single-element array containing dropped text
Self for chaining
Throws an Error on failure; wrap calls in try/catch to handle it.