Canvas hit test that ignores transparent pixels
Tap one sticker, a different one moves. My canvas hit test used an oval, not the art. A 64×64 alpha mask per sprite fixed overlapping picks.
Contents
The symptom fit in one line: press one piece and another one drags. That was in Find the Brainrot, a hidden-object game where stickers lie in a cluttered pile on a table and you slide them around to find the ones on your list. The stickers are drawn on a 2D canvas, they overlap, they are rotated, and every one of them is a 256×256 picture with a transparent margin round the object.
The fix was to hit test the transparent pixels properly — to let a touch on a sprite's see-through part fall through to whatever is drawn underneath. This post is that fix, the numbers that explained the bug, and a second, related one from another game: the drop end of the same drag.
The setup
The table is a shared package, like most of my game code
(one engine, many games). It runs in a Capacitor WebView,
draws with canvas 2D, and gives each sticker a physics body (matter-js) so a piece you drag
shoves its neighbours. Each sticker carries a position, an angle, a size and a z, its
height in the pile.
Picking a piece is one function: given a point on the table, which sticker is the finger on? Here is a simplified version of what it did:
// Simplified example of the old hit test.
function pieceAt(x, y, pieces, reach = 0.42) {
let best = null;
for (const p of pieces) {
// the touch, in the sticker's own unrotated frame
const dx = x - p.x, dy = y - p.y;
const lx = dx * Math.cos(-p.angle) - dy * Math.sin(-p.angle);
const ly = dx * Math.sin(-p.angle) + dy * Math.cos(-p.angle);
const rx = p.width * reach, ry = p.height * reach;
const inside = (lx * lx) / (rx * rx) + (ly * ly) / (ry * ry) <= 1;
if (inside && (!best || p.z > best.z)) best = p;
}
return best;
}
Rotate the touch into the sticker's frame, check it against an ellipse reaching 42% of the sticker's size each way, and keep the highest one. The ellipse is 84% of the square across, the same oval for a frying pan and for a pair of reading glasses.
Why the oval picked the wrong sprite
The question was how much of that oval is actually art. I measured the stickers' alpha channel: the bounding box of the solid part, as a share of the square. Across a sample of 200 of the 440 stickers, the median was 83% each way and the narrowest was 37%.
So the oval was wrong in two directions, and overlap turned both into the wrong pick:
- A thin sticker on top steals touches through its empty sides. A ladle or a toothbrush lying across a towel has an oval that covers plenty of towel. Press the visible towel next to the ladle's handle and the ladle is the highest thing whose oval contains the point, so the ladle moves.
- A boxy sticker loses its own corners. A square object's corner sits outside any ellipse inscribed in the square. Press the visible corner of a tea towel that lies over something else and the touch goes to the sticker underneath.
While writing this up I re-measured all 440 stickers on a 64×64 grid, this time asking the question the hit test actually cares about. Inside the old oval, the median sticker is 31% see-through. For the ladle it is 67%, and the worst are a candle, a flute and a toothbrush at 73%. In the other direction, the median sticker has 4% of its solid art outside the oval and the worst, a teaspoon and a flute, have 24%. The tea towel has only 2% outside, but those 2% are the corners, and a corner is where I took hold of it on the emulator.
The geometry alone explains both failures. The hit test was asking about a shape nobody had drawn.
Hit testing the alpha mask
The art already says where the object is: the alpha channel. So each sticker now gets a small mask, read once when its image loads, and the hit test asks the mask.
// Simplified example: one 64×64 mask per image, read once on load.
const MASK = 64, SOLID_ALPHA = 48;
function maskOf(img) {
try {
const c = document.createElement('canvas');
c.width = c.height = MASK;
const ctx = c.getContext('2d', { willReadFrequently: true });
ctx.drawImage(img, 0, 0, MASK, MASK);
const { data } = ctx.getImageData(0, 0, MASK, MASK);
const mask = new Uint8Array(MASK * MASK);
for (let i = 0; i < mask.length; i++) mask[i] = data[i * 4 + 3] >= SOLID_ALPHA ? 1 : 0;
return mask;
} catch {
return null; // no canvas (a test runner), or a tainted canvas (cross-origin art)
}
}
function solidAt(mask, u, v) { // u, v from 0 to 1 across the unrotated art
const col = Math.min(MASK - 1, Math.floor(u * MASK));
const row = Math.min(MASK - 1, Math.floor(v * MASK));
return mask[row * MASK + col] === 1;
}
In pieceAt, the touch is already in the sticker's unrotated frame, so u = lx / width + 0.5
and v = ly / height + 0.5. If the point is inside the sticker's square and a mask exists,
the mask decides. If there is no mask yet, the old ellipse decides. That fallback covers the
first frames before an image has loaded, a test environment like jsdom that has no canvas,
and art served from another origin, where getImageData throws on the tainted canvas.
Each mask is 4,096 bytes and costs one drawImage and one getImageData per image, once. A
cell is a 4×4 block of the 256-pixel art. I did not measure whether a coarser grid would do;
64 was the first size I tried, and it held up in the emulator run below.
The highest sticker that is solid under the finger wins. A touch on a see-through margin passes down the pile to the next sticker, and to the bare table if nothing is solid there.
The tie rule I nearly changed
Rewriting the loop, I split the old one-line condition in two: skip a piece lower than the
current best, then test whether the touch hits it. The first version skipped with
p.z < best.z. That quietly changes who wins a tie. The old p.z > best.z kept the first
piece found at equal height; the new loop would have handed it to the last. Skipping with
p.z <= best.z keeps the old behaviour. It is a one-character difference and the kind of
thing nobody notices until two stickers share a height.
What proved it
Two new unit tests pin the new shape down. One builds a sticker whose art is a thin upright bar, solid only in the middle third, lying over another sticker. A touch on its clear left side returns the sticker underneath, a touch on the bar returns the bar, and a touch on its clear right side, over bare table, returns nothing. The other checks that a fully solid square sticker can be picked at its corner, past where the ellipse reached. The package went from 33 to 35 passing tests, and the game's 927 tests stayed green.
Then the emulator, in the gesture mode where whatever you touch moves. I dragged the tea towel from its top-left corner, a spot the old oval did not cover, and the tea towel moved. It was blocked part of the way by the stickers round it, which is the physics doing its job. Then I dragged the ladle by its bowl, and the ladle moved.
What I did not do is record the old build making the wrong pick on the emulator before the fix. The cause rests on the geometry above, which does not leave much room for doubt, and on the fixed build picking correctly at points the old oval got wrong. I only ran it on Android.
The other end of the drag: where it lands
Six days earlier, in ASMR Logo Craft Block, I had the mirror image of this bug. Drag and drop felt very strict: I would let go of a block clearly over a tile and it flew back to its slot.
That game is DOM, not canvas, and the drop target was whatever document.elementFromPoint
returned at the centre of the held block. One point, again. It came back empty in three
places:
- the gaps between tiles, 11 px between columns and 9 px between rows on a phone, which add up to about a quarter of the board;
- the rounded corners of each tile;
- just past the board's edge, even with the block half over the outer tile.
My first fix took the tile nearest the block's centre, up to half a tile away. It passed 48 out of 48 browser cases in Chromium and WebKit, and it still felt wrong in the hand. Two reasons. The block's own slot counted as a candidate, so a block covering 40% of a neighbour still had its centre nearer home and went back there. And on touch the block is drawn about 58 px above the finger, so it stays visible; dragging down one row left the block covering 40% of the tile below while its centre had barely left the slot. My 48 cases were gaps, corners and edges. None of them was "mostly still over its own slot", because that was not the rule I had in mind when I wrote them.
The rule that shipped asks about area:
// Simplified example: drop on the tile the block covers most.
function dropTarget(block, tiles, minCover = 0.25) {
let best = null, bestShare = minCover;
for (const t of tiles) {
if (t.isHome || t.heldByOtherFinger || t.solving) continue;
const w = Math.min(block.right, t.right) - Math.max(block.left, t.left);
const h = Math.min(block.bottom, t.bottom) - Math.max(block.top, t.top);
if (w <= 0 || h <= 0) continue;
const share = (w * h) / (t.width * t.height);
if (share >= bestShare) { best = t; bestShare = share; }
}
return best;
}
The rectangles are the tiles as drawn, so a tile still sliding into place counts where you can see it, and the glow under the block uses the same function, so it shows exactly where the block will land. It passed 39 of 39 browser cases in Chromium and WebKit at phone and iPad sizes, including the two cases above, which the nearest-centre rule had sent back. The original point check had refused every gap, corner and edge drop in the first set.
One thing is still open. A two-finger stress test sometimes loses 1 drag in 10. I built the same app with the original drop code and it fails the same way, so it predates this change, and I have not found its cause.
Takeaway
Both bugs asked "what is under this point?" and answered with a shape the player never sees. The pick-up used an oval where the art had a ladle; the drop used one point where the player saw a whole block over a tile. A hit test is right when it agrees with the picture, and the picture is the data you already have: the alpha channel for a sprite, the drawn rectangles for a tile.
The cheaper lesson is about the test cases. My first drop fix passed every case I wrote, because I wrote them from the rule. The case that mattered came from playing it on a phone.