In this lesson Raka's coffee print becomes a design customers can arrange: the cup, the word BREW and the round "R" sticker can be touched, dragged and given a different ink colour. Yet a canvas only keeps pixels. So how do you know which sticker was touched?
Picture Raka's print board in the shop window: a customer points at "the round one" behind the glass. The glass doesn't know what is being pointed at. Raka knows, because he has notes: the round sticker is here, the cup is there. On a canvas, those notes are your own array of objects, and matching the finger's position against them is called hit testing.
A canvas only knows pixels
Ordinary HTML elements (and SVG) are objects in the DOM: a button can get its own addEventListener('click'). A canvas only keeps pixels. Once the cup is drawn, there's no "cup" object to attach a listener to. So you keep the design yourself, and draw it from that data:
const design = [
{ kind: 'cup', x: 150, y: 165, ink: '#c47a3d' },
{ kind: 'text', x: 150, y: 282, width: 134, ink: '#f5e6c8' }, // width: measureText('BREW').width, rounded
{ kind: 'sticker', x: 235, y: 70, r: 28, ink: '#c47a3d' },
];
function draw() {
ctx.clearRect(0, 0, 300, 300);
for (const thing of design) drawThing(thing); // drawing order = stacking order
}
There's only one listener, on the canvas, and on every touch you find out yourself which thing was hit. After the data changes (a position or an ink), call draw() again.
Other options for a canvas whose objects can be clicked and dragged:
| Way | When to pick it |
|---|---|
| Write it yourself (this lesson) | a few objects and simple rules. You understand every step, and there is no extra library. Pick this for learning |
| Konva or Fabric.js (canvas libraries) | many objects that can be dragged, turned and resized. The library keeps each thing as an object and does the hit testing itself. In Konva, draggable: true is enough. In Fabric.js every object can be dragged right away, and it gets handles to resize and turn it |
| SVG | only a few shapes. Each shape is an element in the DOM, so it can get its own addEventListener |
Pointer events
pointerdown, pointermove and pointerup are one set of events for the mouse, a finger and a stylus at once, so you don't write separate mouse... and touch... versions.
canvas.addEventListener('pointerdown', startDrag);
canvas.addEventListener('pointermove', drag);
canvas.addEventListener('pointerup', endDrag);
canvas.addEventListener('pointercancel', endDrag);
canvas { touch-action: none; } /* a finger on the canvas doesn't scroll the page */
Without touch-action: none, on a phone the browser treats a moving finger as a scroll: the page moves, then the browser sends pointercancel and the drag stops. preventDefault() in a pointer event can't stop that scroll; touch-action can.
From the screen to canvas coordinates
e.clientX and e.clientY are the pointer's position in the browser window. canvas.getBoundingClientRect() gives the canvas's position and size in the same window. Subtract its top-left corner (rect.left, rect.top), then scale to the drawing's 300 units:
function canvasPoint(e) {
const rect = canvas.getBoundingClientRect();
return {
x: (e.clientX - rect.left) * (300 / rect.width),
y: (e.clientY - rect.top) * (300 / rect.height),
};
}
On a phone, the canvas shows at 240 px, with rect.left 40 and rect.top 100. A customer touches at clientX 160, clientY 220:
| Step | x | y |
|---|---|---|
| Minus the canvas corner | 160 - 40 = 120 | 220 - 100 = 120 |
| Times 300 / 240 = 1.25 | 150 | 150 |
The touched point is (150, 150), the middle of the drawing. Without the × 1.25, the code thinks it's (120, 120): 30 px off towards the top left, and the sticker that was touched doesn't get picked.
The 300 here is the drawing's units, because we draw through setTransform(dpr, 0, 0, dpr, 0, 0) (the Canvas API Basics lesson). If you draw straight in the canvas's real pixels, use canvas.width / rect.width.
Hit testing with maths
The round sticker is hit when the pointer's distance to its centre is no more than its radius. The distance comes from Pythagoras, and to skip Math.sqrt, compare the squares:
function hitsCircle(s, x, y) {
const dx = x - s.x;
const dy = y - s.y;
return dx * dx + dy * dy <= s.r * s.r;
}
function hitsBox(t, x, y) {
return x >= t.x - t.width / 2 && x <= t.x + t.width / 2 &&
y >= t.y - 33 && y <= t.y + 1; // text: 33 px above the baseline, 1 px below it
}
The sticker at (235, 70) with r 28, touched at (250, 84): dx 15, dy 14, so 225 + 196 = 421. The limit is 28 × 28 = 784. 421 ≤ 784, a hit. The version Math.sqrt(dx * dx + dy * dy) < r means the same, it's just a little slower.
Hit testing with isPointInPath
The cup's body is a trapezoid, and its formula is a chore. Keep the shape as a Path2D (a path you can reuse), then ask the canvas:
const cupBody = new Path2D();
cupBody.moveTo(-55, -45); // relative to the cup's centre
cupBody.lineTo(55, -45);
cupBody.lineTo(45, 45);
cupBody.lineTo(-45, 45);
cupBody.closePath();
function hitsCup(c, x, y) {
ctx.save();
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.translate(c.x, c.y);
// the point is in real canvas pixels: the transform doesn't apply to it
const hit = ctx.isPointInPath(cupBody, x * dpr, y * dpr);
ctx.restore(); // put the transform back, so the next draw() is not moved too
return hit;
}
- The path is moved and scaled by the current transform, just as when it was drawn.
- The point
x,yis not transformed: it's read as real canvas pixels. On a DPR 2 screen, the cup's middle (150, 165) has to be sent as (300, 330). Sent as (150, 165), the answer isfalse.
Dragging
let held = null;
let offset = { x: 0, y: 0 };
function startDrag(e) {
const p = canvasPoint(e);
// from the top: what was drawn last is checked first
for (let i = design.length - 1; i >= 0; i--) {
if (hits(design[i], p.x, p.y)) {
held = design[i];
offset = { x: p.x - held.x, y: p.y - held.y };
canvas.setPointerCapture(e.pointerId);
return;
}
}
}
function drag(e) {
if (!held) return;
const p = canvasPoint(e);
held.x = p.x - offset.x;
held.y = p.y - offset.y;
draw();
}
function endDrag() {
held = null;
}
offsetkeeps the pointer's distance to the thing's centre. Without it, the thing jumps until its centre sits right under the finger.setPointerCapturekeepspointermoveandpointerupcoming to the canvas even when the pointer leaves it.
Keyboard and screen readers
A canvas has no elements inside it, so the Tab key can't pick the cup, and a screen reader only finds one picture. What you offer instead:
- Real buttons beside the canvas for every action: pick a thing, move it 10 px in four directions, change the ink. Buttons can be focused and pressed with Enter or Space.
- A status that gets read out:
<p aria-live="polite">Sticker selected, x 235, y 70, brown ink</p>, updated on every change. - A description of the canvas:
role="img"and anaria-labelthat describes the design. Text between<canvas>and</canvas>is a fallback for browsers that can't draw a canvas.
⚠️ Touches that miss and drags that stop
- Forgetting the scale.
e.clientX - rect.leftalone is only right when the canvas shows at exactly 300 px. On a 240 px phone, a press is 30 px off in the middle, and more at the right edge. - isPointInPath's point not multiplied by dpr. The path follows the transform, the point doesn't. On a retina screen, send
x * dprandy * dpr. - A hit test without
save()/restore(). Thetranslateinside it still applies after the function ends, soclearRect(0, 0, 300, 300)indraw()clears the wrong place, and the dragged cup leaves a trail. - Checking from the bottom. When the sticker sits on top of the cup, check from what was drawn last, so the picked thing is the one you see on top.
- No
touch-action: none. On a phone, a drag turns into a scroll and stops halfway.
TL;DR: A canvas only keeps pixels, so keep your design as an array of objects and redraw from it. Use pointer events (pointerdown/move/up), and convert the position: (e.clientX - rect.left) * (300 / rect.width), and y the same way with rect.top. Hit testing: circles with dx * dx + dy * dy <= r * r, boxes by comparing x and y, other shapes with isPointInPath(path, x * dpr, y * dpr), because the point isn't transformed. Drag by keeping the distance to the centre and calling setPointerCapture, check from the topmost thing, and set touch-action: none. For keyboards and screen readers, offer real buttons, an aria-live status, and an aria-label on the canvas.
⚡ Keep the design yourself
Write:
const design = [
{ kind: 'cup', x: 150, y: 165, ink: '#c47a3d' },
{ kind: 'sticker', x: 235, y: 70, r: 28, ink: '#c47a3d' },
];
Guess first: can a cup that's already drawn get an addEventListener('click') like a button?
No. A canvas only keeps pixels, so there's no "cup" object to attach a listener to.
Meaning: You keep the design yourself as an array of objects, and redraw from that data after every change. One listener, on the canvas, is enough.
⚡ From the screen to canvas coordinates
Write:
x: (e.clientX - rect.left) * (300 / rect.width),
y: (e.clientY - rect.top) * (300 / rect.height),
Meaning: Subtract the canvas corner, then scale to the drawing's 300 units. On a phone with a 240 px canvas, without the × 1.25 the point is 30 px off towards the top left.
⚡ Hit or miss, with maths
Write:
function hitsCircle(s, x, y) {
const dx = x - s.x;
const dy = y - s.y;
return dx * dx + dy * dy <= s.r * s.r;
}
Meaning: The sticker is hit when the pointer's distance to its centre is no more than its radius. Compare the squares, so there's no need for Math.sqrt.
⚡ Check from the top
Meaning: What was drawn last shows on top, so check from the end of the array: for (let i = design.length - 1; i >= 0; i--). Also set touch-action: none on the canvas, so a drag on a phone doesn't turn into a scroll.