Use Pointer Events to read Canvas input from a mouse, touch screen, or pen with one JavaScript event model. The most common events for Canvas interaction are pointerdown, pointermove, pointerup, pointerenter, and pointerleave.
Move or press a pointer inside the Canvas.
const canvas = document.getElementById('pointer_canvas');
function getCanvasPoint(event) {
const rect = canvas.getBoundingClientRect();
return {
x: (event.clientX - rect.left) * canvas.width / rect.width,
y: (event.clientY - rect.top) * canvas.height / rect.height
};
}
canvas.addEventListener('pointermove', (event) => {
const point = getCanvasPoint(event);
console.log(point.x, point.y, event.pointerType);
});
A Canvas has bitmap dimensions (width/height attributes) and may also have a different CSS display size. getBoundingClientRect() reports the displayed rectangle, so scale the pointer coordinates when those sizes differ.
For drag interactions, call setPointerCapture(event.pointerId) after pointerdown so movement can continue even when the pointer temporarily leaves the Canvas. See the dragging tutorial.
Mouse events remain useful for mouse-only interfaces, and the older jQuery Canvas event example is preserved for legacy code. Pointer Events are more flexible for new work.
Pointer Events are a unified option. pointermove and pointerdown expose clientX and clientY for mouse, touch and pen pointers.
It gives the Canvas position and rendered size in viewport coordinates so pointer positions can be converted correctly.
It reports the pointer source, commonly mouse, pen or touch.
It keeps subsequent pointer events associated with the element during dragging, even if the pointer moves outside its bounds.
No. Provide semantic HTML controls or equivalent accessible interaction for essential tasks.
Drag Canvas shapes | Legacy jQuery events | JavaScript events | Canvas tutorial
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.