CanvasPointer is a utility class designed to manage pointer interactions (mouse, touch, etc.) on a canvas element. It abstracts raw pointerdown, pointermove, and pointerup events into high-level semantic actions like clicks, double-clicks, and drags.
Interaction Lifecycle
Depending on the user's movement and timing, CanvasPointer will trigger one of the following sets of callbacks:
- Click: Triggered if the pointer is released near the original
pointerdown position within the bufferTime. - Double-Click: Triggered if a click occurs within
doubleClickTime of the previous successful click. - Drag: Triggered if the pointer moves beyond the
maxClickDrift threshold or stays down longer than bufferTime.
Key Properties and Configuration
maxClickDrift: The maximum distance (in pixels) the pointer can move from the initial pointerdown position before the interaction is considered a drag instead of a click. Defaults to 6.bufferTime: The maximum time (in milliseconds) to ignore click drift. Defaults to 150.doubleClickTime: The maximum gap (in milliseconds) between pointerup and pointerdown to be considered a double-click. Defaults to 300.clearEventsOnReset: If true (default), calling reset() clears the eDown, eMove, and eUp event references.
Usage Pattern
To use CanvasPointer, you typically instantiate it with a target Element, then hook its down, move, and up methods into your event listeners. You then define the desired behavior using the semantic callback properties.
const pointer = new CanvasPointer(canvasElement);
// Define semantic behaviors
pointer.onClick = (e) => console.log('Clicked at:', e.clientX, e.clientY);
pointer.onDrag = (e) => console.log('Dragging...');
pointer.onDragEnd = (e) => console.log('Drag finished');
// Hook into raw events
canvasElement.addEventListener('pointerdown', (e) => pointer.down(e as CanvasPointerEvent));
canvasElement.addEventListener('pointermove', (e) => pointer.move(e as CanvasPointerEvent));
canvasElement.addEventListener('pointerup', (e) => pointer.up(e as CanvasPointerEvent));