This page preserves the older jQuery approach to Canvas mouse events for developers maintaining legacy code. For new work, prefer Pointer Events with vanilla JavaScript, which handle mouse, touch and pen through one event model.
The live demo uses native JavaScript so it works even when jQuery is loaded later by a shared template. The equivalent jQuery code is shown directly below for developers maintaining older code.
const canvas = $('#jq_event_canvas').get(0);
$('#jq_event_canvas').on('mousemove mousedown mouseup click', function (event) {
const rect = canvas.getBoundingClientRect();
const x = (event.clientX - rect.left) * canvas.width / rect.width;
const y = (event.clientY - rect.top) * canvas.height / rect.height;
$('#jq_event_output').text(event.type + ': ' + Math.round(x) + ', ' + Math.round(y));
});
Subtracting rect.left and rect.top gives CSS-pixel coordinates. If CSS resizes the Canvas, scale those values into the Canvas bitmap coordinate system using canvas.width / rect.width and canvas.height / rect.height.
canvas.addEventListener('pointermove', (event) => {
const rect = canvas.getBoundingClientRect();
const x = (event.clientX - rect.left) * canvas.width / rect.width;
const y = (event.clientY - rect.top) * canvas.height / rect.height;
});
Pointer Events reduce duplicated mouse/touch logic and are the recommended direction for new interactive Canvas code.
A Canvas-only pointer interface may exclude keyboard and assistive-technology users. Provide equivalent HTML controls or another accessible interaction path for essential actions.
No. This page keeps a jQuery example for legacy maintenance, but native Pointer Events are preferred for new code.
That converts CSS display coordinates into the Canvas bitmap coordinate system when the Canvas is responsively resized.
Pointer Events such as pointerdown, pointermove and pointerup provide a unified model.
No. Native drag events are a separate drag-and-drop system. Custom Canvas dragging is normally built with pointer events.
No. Provide equivalent semantic controls or another accessible workflow for important interactions.
Pointer Events in JavaScript | Drag Canvas shapes | 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.