Why Drag-to-Select Grids Lag on Mobile (and How to Hit 60 FPS with O(1) Math)
Why Drag-to-Select Grids Lag on Mobile (and How to Hit 60 FPS with O(1) Math) #webdev #gamedev #javascript #performance If you have ever built a grid-based web puzzleβa word search, a minesweeper variant, or a number-
Why Drag-to-Select Grids Lag on Mobile (and How to Hit 60 FPS with O(1) Math)
#webdev #gamedev #javascript #performance
If you have ever built a grid-based web puzzleβa word search, a minesweeper variant, or a number-matching boardβyou have probably hit the same mobile wall: everything feels smooth on a desktop mouse, then turns into a slideshow the moment you drag a finger across the screen on a mid-range phone.
The culprit is rarely JavaScript speed. It is almost always layout thrashing inside pointermove.
When I profiled a 10Γ17 (170-cell) number-matching grid prototype on a throttled mobile CPU, frame times spiked to 42 ms during a simple diagonal dragβdropping the frame rate to ~23 FPS. Switching from DOM hit-testing to cached coordinate math brought frame times down to 4.8 ms (locked 60 FPS) with zero framework changes.
1. The Hidden Trap: Calling getBoundingClientRect() on Every Move
The most intuitive way to build a drag-selection box is to draw a rectangle from (startX, startY) to (currentX, currentY), then loop through every cell on the board to see which ones overlap:
// The classic 20 FPS trap
function handlePointerMove(e) {
const selectionBox = getSelectionRect(startX, startY, e.clientX, e.clientY);
cells.forEach((cell) => {
// Forces a synchronous style & layout check 170 times per frame
const rect = cell.getBoundingClientRect();
const isHit = rectsOverlap(selectionBox, rect);
cell.classList.toggle('selected', isHit);
});
}
On a 170-cell board, a single pointermove event triggers 170 DOM measurements and potentially dozens of class mutations. Because pointermove fires at 60β120 Hz on modern touchscreens, the browser spends the entire frame budget recalculating layout instead of painting.
Fast-paced browser puzzlesβsuch as a classic fruit box puzzle game https://fruitboxgames.app/ where players rapidly box groups of tiles that sum to 10 against a countdownβdepend on instant tactile feedback. Even a 30 ms hiccup makes the selection rectangle feel sticky and causes players to miss combos.
2. Baseline Profile: Measure Before Rewriting
Before touching the rendering layer, I ran a 5-second drag trace in Chrome DevTools with 4Γ CPU slowdown enabled on a production build.
| Metric | Baseline (DOM Hit-Test) | Target |
|---|---|---|
| Average Frame Time (during drag) | 41.8 ms | Under 16.6 ms |
Scripting + Layout per pointermove
|
34.2 ms | Under 5 ms |
| Forced Reflows per Second | ~10,200 | 0 |
| Dropped Frames (5s drag test) | 64% | Under 2% |
The flame graph confirmed that 81% of main-thread time was spent inside Recalculate Style and Layout, not in the game's actual sum-checking logic.
3. Fix 1: Replace DOM Queries with O(1) Grid Math
A uniform grid already has a predictable geometry. Instead of asking the browser where all 170 cells are on every pixel of finger movement, measure the grid container once (on pointerdown and resize), then map pointer coordinates directly to (row, col) indices.
let boardRect = null;
const COLS = 17;
const ROWS = 10;
function handlePointerDown(e) {
boardRect = gridElement.getBoundingClientRect();
e.currentTarget.setPointerCapture(e.pointerId);
// store startX, startY...
}
function getSelectedBounds(startX, startY, currX, currY) {
const cellW = boardRect.width / COLS;
const cellH = boardRect.height / ROWS;
const minX = Math.min(startX, currX) - boardRect.left;
const maxX = Math.max(startX, currX) - boardRect.left;
const minY = Math.min(startY, currY) - boardRect.top;
const maxY = Math.max(startY, currY) - boardRect.top;
return {
colStart: Math.max(0, Math.floor(minX / cellW)),
colEnd: Math.min(COLS - 1, Math.floor(maxX / cellW)),
rowStart: Math.max(0, Math.floor(minY / cellH)),
rowEnd: Math.min(ROWS - 1, Math.floor(maxY / cellH)),
};
}
With this approach:
-
Zero
getBoundingClientRect()calls happen duringpointermove. - You only diff the
colStart..colEndandrowStart..rowEndindices. If the finger moves 4 pixels inside the same cell, no DOM updates run at all.
4. Fix 2: Batch Visual Updates with requestAnimationFrame
High-refresh-rate phones (90 Hz or 120 Hz) can fire multiple pointermove events before the browser is ready to paint a single frame. Decouple input capture from visual updates:
let rafId = null;
let latestPoint = null;
function handlePointerMove(e) {
latestPoint = { x: e.clientX, y: e.clientY };
if (!rafId) {
rafId = requestAnimationFrame(() => {
updateSelectionBox(latestPoint.x, latestPoint.y);
updateHighlightedCells(latestPoint.x, latestPoint.y);
rafId = null;
});
}
}
And for the selection rectangle itself, avoid mutating width, height, top, and left. Position it with transform: translate3d(x, y, 0) scale(sx, sy) and transform-origin: top left so the GPU compositor handles the overlay without triggering layout.
5. Fix 3: Lock Mobile Touch Ergonomics
Two tiny CSS properties prevent mobile browsers from fighting your drag gesture:
.game-grid {
touch-action: none; /* Stops pull-to-refresh and page scroll during drags */
user-select: none; /* Prevents accidental text-selection highlights */
-webkit-user-select: none;
}
Using setPointerCapture(e.pointerId) on pointerdown also guarantees that if a player's thumb drifts slightly outside the board edge, the drag still resolves cleanly on pointerup instead of getting stuck.
6. Final Results: Before vs. After
Re-running the exact same 5-second diagonal drag trace under 4Γ CPU throttling showed the impact immediately:
| Metric | Before | After | Change |
|---|---|---|---|
| Average Frame Time | 41.8 ms | 4.8 ms | -88% |
| Scripting + Layout / move | 34.2 ms | 1.9 ms | -94% |
| Forced Reflows / sec | ~10,200 | 0 | Eliminated |
| Dropped Frames | 64% | 0.8% | Locked 60 FPS |
You do not always need to rewrite a DOM-based puzzle game in WebGL or Canvas to get native-feeling mobile performance. Caching container geometry, doing hit-testing with O(1) index math, and batching renders inside requestAnimationFrame removes the real bottleneckβletting the browser focus on smooth 60 FPS gameplay.
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.