Skip to content

Instantly share code, notes, and snippets.

@MarekZeman91
Created September 10, 2025 15:46
Show Gist options
  • Select an option

  • Save MarekZeman91/bdc35dfbfb03fdbea387790881a17e12 to your computer and use it in GitHub Desktop.

Select an option

Save MarekZeman91/bdc35dfbfb03fdbea387790881a17e12 to your computer and use it in GitHub Desktop.
Manage cursor on canvas or SVG easily by determining the cursor and importance level
export enum CursorLevel {
chart,
shape,
text,
handle,
}
const instances = new WeakMap<HTMLElement, CursorManager>()
export class CursorManager {
readonly #levels: Array<string | undefined> = []
readonly #element: HTMLElement
readonly #default: string
#qid = 0
#current: string = ''
static get(element: HTMLElement, defaultCursor: string = 'default') {
instances.set(element, instances.get(element) ?? new CursorManager(element, defaultCursor))
return instances.get(element)!
}
private constructor(element: HTMLElement, defaultCursor: string) {
this.#element = element
this.#default = defaultCursor
this.set(defaultCursor, CursorLevel.chart)
}
get(): string {
return this.#current
}
set(cursor: string, level: CursorLevel) {
this.#levels[level] = cursor
this.#update()
}
clear(level: CursorLevel) {
this.#levels[level] = undefined
this.#update()
}
#update() {
window.cancelAnimationFrame(this.#qid)
this.#qid = window.requestAnimationFrame(() => {
const highestLevel = this.#levels.findLastIndex(Boolean)
const newCursor = this.#levels[highestLevel] ?? this.#default
if (this.#current === newCursor) return
this.#current = newCursor
this.#element.style.cursor = newCursor
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment