Created
September 10, 2025 15:46
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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