Last updated: December 4, 2026.
Use pointer events to hit-test the circle, store where the pointer grabbed it and update its center during the drag. Pointer capture keeps delivering movement to the canvas when the pointer leaves its bounds.
const canvas = document.querySelector('#board');
const ctx = canvas.getContext('2d');
const circle = { x: 80, y: 65, radius: 24 };
let drag = null;
function position(event) {
const rect = canvas.getBoundingClientRect();
return {
x: (event.clientX - rect.left) * canvas.width / rect.width,
y: (event.clientY - rect.top) * canvas.height / rect.height,
};
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(circle.x, circle.y, circle.radius, 0, 2 * Math.PI);
ctx.fill();
}
canvas.addEventListener('pointerdown', event => {
if (drag || event.button !== 0) return;
const p = position(event);
if (Math.hypot(p.x - circle.x, p.y - circle.y) > circle.radius) return;
canvas.setPointerCapture(event.pointerId);
drag = { id: event.pointerId, dx: p.x - circle.x, dy: p.y - circle.y };
});
canvas.addEventListener('pointermove', event => {
if (event.pointerId !== drag?.id) return;
const p = position(event);
circle.x = p.x - drag.dx;
circle.y = p.y - drag.dy;
draw();
});
for (const type of ['pointerup', 'pointercancel', 'lostpointercapture']) {
canvas.addEventListener(type, event => {
if (event.pointerId === drag?.id) drag = null;
});
}
draw();Set up the canvas and scale the coordinates
Load the script after a visible 320 by 180 canvas with ID board. Put borders and padding on a wrapper. The ratios account for CSS scaling.
Set touch-action: none on the drag surface. Provide keyboard controls for essential actions.
Track one pointer from start to finish
The offset prevents jumps. Test an off-center grab, a release outside the canvas, and cancellation.