hs.canvas
Modulehs.canvas
A low-level, absolutely-positioned drawing surface
hs.canvas mirrors v1 Hammerspoon's hs.canvas module: elements are plain JS
objects (mirroring v1's Lua tables) describing shapes (rectangle, circle,
oval, text) with a fill/stroke/strokeAndFill/clip/build/skip action
pipeline. This is a different tool from hs.ui, which is a SwiftUI stack/layout
builder for app-like interfaces -- reach for hs.canvas when you need absolute
positioning, clipped/composited shapes, or direct window-level/Spaces control.
Coordinates
A canvas's window position (create({x, y, w, h}), frame(), setFrame(),
topLeft()) uses the same screen coordinates as hs.screen, hs.window and
hs.ui.window: y = 0 is the top of the primary screen, and y increases downward.
You can pass a window's or screen's frame straight to create() or setFrame().
Element content positioned inside a canvas -- every frame, center, and
coordinates value you pass to appendElements() and friends -- is relative to the
canvas: {x: 0, y: 0} is the canvas's top-left corner, and y increases downward.
Example: a rounded screen corner overlay
const radius = 12
const corner = hs.canvas.create({x: 0, y: 0, w: radius, h: radius})
corner.appendElements([
{ action: "build", type: "rectangle" },
{ action: "clip", type: "circle", center: {x: radius, y: radius}, radius: radius, reversePath: true },
{ action: "fill", type: "rectangle", fillColor: { alpha: 1 } },
{ type: "resetClip" }
])
corner.levelValue(hs.canvas.windowLevels.screenSaver + 1)
corner.behavior("canJoinAllSpaces")
corner.show()
Types
This module provides the following types:
Object Types
Plain JavaScript objects that this module's methods and properties take or return:
HSCanvasElement
One element drawn on a canvas. Only type is required; see the canvas guide for what each attribute does and which element types read it. Positions and sizes are numbers of points, or percentage strings such as "50%" of the canvas's size
| Field | Type | Description |
|---|---|---|
| type | "rectangle" | "circle" | "oval" | "arc" | "ellipticalArc" | "segments" | "points" | "text" | "image" | "canvas" | "resetClip" | The kind of element |
| action optional | "fill" | "stroke" | "strokeAndFill" | "build" | "clip" | "skip" | How the element's shape is drawn. Defaults to "strokeAndFill" |
| compositeRule optional | string | A blend mode for this element only, one of the names in hs.canvas.compositeTypes |
| id optional | any | Your own value for the element, passed back to mouse callbacks |
| trackMouseDown optional | boolean | Report left mouse button presses on the element to the mouse callback |
| trackMouseUp optional | boolean | Report left mouse button releases on the element to the mouse callback |
| trackRightMouseDown optional | boolean | Report right mouse button presses on the element to the mouse callback |
| trackRightMouseUp optional | boolean | Report right mouse button releases on the element to the mouse callback |
| trackMouseEnterExit optional | boolean | Report the mouse entering and leaving the element to the mouse callback |
| trackMouseMove optional | boolean | Report the mouse moving over the element to the mouse callback |
| rotation optional | number | Degrees to rotate the element by, about rotationPoint |
| rotationPoint optional | object | The point to rotate about. Defaults to the centre of the element's bounds |
| x optional | number | string | |
| y optional | number | string | |
| transformation optional | object | An affine transformation matrix, used instead of rotation. Missing entries are the identity matrix's |
| m11 optional | number | |
| m12 optional | number | |
| m21 optional | number | |
| m22 optional | number | |
| tX optional | number | |
| tY optional | number | |
| windingRule optional | "nonZero" | "evenOdd" | How overlapping parts of a built-up path are filled. Defaults to "nonZero" |
| fillColor optional | string | HSColor | HSCanvasColor | The colour to fill the shape with |
| strokeColor optional | string | HSColor | HSCanvasColor | The colour to outline the shape with |
| strokeWidth optional | number | The width of the shape's outline |
| fillGradient optional | "linear" | "radial" | Fill with a gradient instead of fillColor |
| fillGradientColors optional | (string | HSColor | HSCanvasColor)[] | The gradient's colours, at least two, evenly spaced |
| fillGradientAngle optional | number | The angle of a linear gradient, in degrees. Defaults to 0 |
| fillGradientCenter optional | object | The centre of a radial gradient. Defaults to the centre of the shape's bounds |
| x optional | number | string | |
| y optional | number | string | |
| frame optional | object | The bounds of a rectangle, oval, ellipticalArc, text, image or canvas. Defaults to the whole canvas; a missing x or y is 0, and a missing w or h is the canvas's |
| x optional | number | string | |
| y optional | number | string | |
| w optional | number | string | |
| h optional | number | string | |
| roundedRectRadii optional | number | {xRadius?: number, yRadius?: number} | The corner radius of a rectangle |
| center optional | object | The centre of a circle or arc. Defaults to the centre of the canvas |
| x optional | number | string | |
| y optional | number | string | |
| radius optional | number | string | The radius of a circle or arc. Defaults to half the canvas's shorter side |
| reversePath optional | boolean | Reverse the direction of a circle's path, to cut a hole with build and clip |
| startAngle optional | number | Where an arc or ellipticalArc starts, in degrees. Defaults to 0 |
| endAngle optional | number | Where an arc or ellipticalArc ends, in degrees. Defaults to 360 |
| arcClockwise optional | boolean | Draw an arc or ellipticalArc clockwise. Defaults to false |
| arcRadii optional | boolean | Also draw the lines from an arc's centre to its ends. Defaults to false |
| coordinates optional | object[] | The points of a segments or points element. c1x/c1y/c2x/c2y curve a segment into its point |
| x optional | number | string | |
| y optional | number | string | |
| c1x optional | number | string | |
| c1y optional | number | string | |
| c2x optional | number | string | |
| c2y optional | number | string | |
| closed optional | boolean | Join the last point of a segments element back to its first. Defaults to false |
| text optional | string | The text of a text element |
| textSize optional | number | The text's font size. Defaults to 27 |
| textColor optional | string | HSColor | HSCanvasColor | The text's colour. Defaults to black |
| textFont optional | string | The PostScript name of the text's font, e.g. "Menlo-Bold" |
| textWeight optional | "thin" | "ultraLight" | "light" | "regular" | "medium" | "semibold" | "bold" | "heavy" | "black" | The text's weight, if textFont isn't set |
| textDesign optional | "monospaced" | "rounded" | "serif" | The design of the system font, if textFont isn't set |
| textItalic optional | boolean | Whether the text is italic |
| textAlignment optional | "left" | "right" | "center" | "justified" | "natural" | How the text is aligned. Defaults to "natural" |
| textLineBreak optional | "wordWrap" | "charWrap" | "clip" | "truncateHead" | "truncateMiddle" | "truncateTail" | How text that doesn't fit is wrapped or cut. Defaults to "wordWrap" |
| image optional | HSImage | The image of an image element |
| imageAlpha optional | number | The image's opacity. Defaults to 1 |
| imageScaling optional | "none" | "scaleToFit" | "scaleProportionally" | "shrinkToFit" | How the image is scaled to its frame. Defaults to "scaleProportionally" |
| imageAlignment optional | "center" | "top" | "bottom" | "left" | "right" | "topLeft" | "topRight" | "bottomLeft" | "bottomRight" | Where the image sits in its frame. Defaults to "center" |
| canvas optional | HSCanvas | The canvas a canvas element draws |
| canvasAlpha optional | number | The nested canvas's opacity. Defaults to 1 |
HSCanvasColor
A colour as an object, as hs.drawing.color took them in Hammerspoon 1. Components are from 0 to 1; ones you leave out are 0, except alpha, which is 1. The first of list/name, hex, white and hue/saturation/brightness that's present is used, otherwise red/green/blue
| Field | Type | Description |
|---|---|---|
| red optional | number | |
| green optional | number | |
| blue optional | number | |
| alpha optional | number | |
| hue optional | number | |
| saturation optional | number | |
| brightness optional | number | |
| white optional | number | |
| hex optional | string | A hex colour, e.g. "#4A90E2" |
| list optional | string | The name of a system colour list, e.g. "Apple" |
| name optional | string | The name of a colour in list |
Properties
hs.canvas.windowLevels
Named window levels, exposed as raw numeric values (not opaque strings) so scripts can do arithmetic on them, matching v1 behavior.
hs.canvas.windowBehaviors
Named window Spaces/Exposé collection behaviors, exposed as raw numeric bit values.
hs.canvas.compositeTypes
Named compositing/blend rules usable as an element's compositeRule attribute.
Methods
hs.canvas.create(rect) -> HSCanvas
Create a new canvas
Named create() rather than v1's new() -- new cannot be used as a
JavaScriptCore-exported method name (it collides with the JS new operator
keyword at the bridging layer), and this codebase's conventions additionally
forbid method names starting with new/alloc/copy (an ARC/ObjC hazard).
hs.canvas.create(rect) -> HSCanvas
| Name | Type | Description |
|---|---|---|
| rect | HSRect | {x: number, y: number, w: number, h: number} | The canvas window's frame: an HSRect (e.g. a window's or screen's frame) or a {x, y, w, h} dictionary, with y = 0 at the top of the primary screen |
const c = hs.canvas.create({x: 100, y: 100, w: 200, h: 200})
const overlay = hs.canvas.create(hs.window.focusedWindow().frame)
hs.canvas.animate(options, changes) -> Promise<boolean>
Animate changes to one or more canvases
Calls changes straight away, and animates every change it makes to a canvas from
its current value to the new one, over options.duration seconds. The changes can be
to any number of elements, on any number of canvases, and all animate together.
Inside changes, these animate:
- element attributes set with
setElementAttribute(),assignElement()(each attribute that differs),rotateElement(),rotateElementAroundPoint()andsetElementTransformation():frame,center,radius,coordinates(with the same number of points),rotation,rotationPoint,transformation,strokeWidth,startAngle,endAngle,roundedRectRadii,textSize,imageAlpha,canvasAlpha,fillColor,strokeColor,textColor,fillGradientColors(with the same number of colors),fillGradientAngleandfillGradientCenter setTransformation()andclearTransformation()- the window, with
setFrame(),setTopLeft(),setSize()andsetAlpha(), while the canvas is showing
Everything else (e.g. text, type, action, or adding and removing elements) changes
immediately, as it does outside animate(). A number and a percentage animate between
each other (e.g. a frame width of "100%" to 50).
Getters return the new values as soon as changes returns, not the values being drawn
part way through the animation. Mouse tracking follows what's drawn.
Changing an attribute that's already animating (inside or outside another animate())
replaces that animation, starting from where it had got to on screen. Calls can be
nested: changes inside a nested call use its options.
If changes throws, the error propagates to the caller, and the changes made before
the error still animate.
hs.canvas.animate(options, changes) -> Promise<boolean>
| Name | Type | Description |
|---|---|---|
| options | object | {duration, curve}. duration is in seconds (default 0.25; 0 makes the changes without animating them). curve is "linear", "easeIn", "easeOut", "easeInOut" (the default), or a cubic bezier [x1, y1, x2, y2] like CSS's cubic-bezier(), with x1 and x2 between 0 and 1 |
| duration optional | number | |
| curve optional | "linear" | "easeIn" | "easeOut" | "easeInOut" | [number, number, number, number] | |
| changes | () => void | A function that changes canvases |
true if every change ran to completion, or false if any was interrupted (by another change to the same attribute, its element or attribute being removed, or its canvas being destroyed)const c = hs.canvas.create({x: 100, y: 100, w: 400, h: 300}).show()
c.appendElements([{type: "rectangle", frame: {x: 10, y: 10, w: 50, h: 50}, fillColor: "#3366FF"}])
// Move, resize, recolour and rotate the rectangle, and move the canvas, all at once
hs.canvas.animate({duration: 0.6, curve: "easeInOut"}, () => {
c.setElementAttribute(0, "frame", {x: 300, y: 200, w: 80, h: 80})
c.setElementAttribute(0, "fillColor", {red: 1, green: 0.3, blue: 0})
c.rotateElement(0, 45)
c.setTopLeft({x: 200, y: 150})
}).then(finished => console.log("Finished: " + finished))