You're absolutely right to seek further optimization — and more importantly, to measure performance and notice that the optimized version might be slower, despite seemingly drawing fewer elements.
✅ Let's clarify the situation and see why that happens, and whether we can do better.
🎯 Goal Recap
You're trying to:
- Scroll a grid-textured background in a direction (
angle) at speed (speed).
- Only draw UI elements within the visible canvas area + required overflow — not waste cycles drawing what will never be seen.
- Use
sin and cos from angle to determine scroll direction, and therefore where overflow is needed.
🧩 Why the Previous Version Got Slower
The main reason the modified version might be slower than expected is:
❗The dynamic loop limits are more complex and may cover more area than the original hardcoded ones!
Original version uses:
for (let y = -height / 2; y < height * 1.5; y += 40)
for (let x = -width / 2; x < width * 1.5; x += 40)
This draws a grid roughly 2x the canvas width and height.
But the modified version uses something like:
const xStart = xScrollDir >= 0 ? -xOverflow : -xOverflow - width;
const xEnd = xScrollDir >= 0 ? width + xOverflow : width + xOverflow + width;
That seems optimized, but in some cases, it will draw 3x the canvas area! Why?
- If scroll direction is negative and
xOverflow is sizable (e.g., 200–300px), you end up drawing from -500 to width + 500 + width.
- That might be even more than the original
-width / 2 to width * 1.5.
In short: we may have traded smarter logic for wider bounds in the worst cases.
🚀 Re-Optimizing the Function
Let’s get the best of both worlds — reduced drawing bounds and predictable performance. Here's a better approach:
✅ Step 1: Calculate visible area + one extra row/column in scroll direction only
✅ Step 2: Keep loop bounds slightly conservative (1 row/col overflow) rather than too smart
Rather than over-optimize xStart to xEnd, we can reduce the loop area by calculating how many "extra tiles" are strictly needed in the scroll direction, while keeping the rest near canvas bounds.
✅ Optimized and Practical Code
function drawBackground(angle, speed) {
console.time("background");
// Clear the canvas
bgCtx.clearRect(0, 0, bgCanvas.width, bgCanvas.height);
// Draw the background color
bgCtx.fillStyle = "black";
bgCtx.fillRect(0, 0, width, height);
// Set up styles
bgCtx.fillStyle = "#181818";
bgCtx.font = "20px monospace";
// Convert angle to radians
const rad = angle * Math.PI / 180;
// Cache trig values if needed
trigFnValues[rad] ??= {
cos: Math.cos(rad),
sin: Math.sin(rad)
};
const { sin, cos } = trigFnValues[rad];
// Update scroll position
bgScrollOffset = (bgScrollOffset + speed) % 300;
// Projected scroll offsets
const offsetX = bgScrollOffset * cos;
const offsetY = bgScrollOffset * sin;
const spacing = 40;
const tileSize = spacing;
// How many extra columns/rows to draw outside viewport
const bufferTiles = 2; // Just enough to avoid artifacts
const cols = Math.ceil(width / spacing) + bufferTiles;
const rows = Math.ceil(height / spacing) + bufferTiles;
const startX = -Math.floor(bufferTiles / 2) * spacing;
const startY = -Math.floor(bufferTiles / 2) * spacing;
bgCtx.save();
for (let row = 0; row < rows; row++) {
const y = startY + row * spacing;
const yOffset = y + spacing / 2 + offsetY;
for (let col = 0; col < cols; col++) {
const x = startX + col * spacing;
const xOffset = x + spacing / 2 + offsetX;
// Apply rotation and position transform
bgCtx.setTransform(cos, sin, -sin, cos, xOffset, yOffset);
bgCtx.fillText(">", 0, 0);
}
}
bgCtx.restore();
console.timeEnd("background");
}
✅ Why This Version Performs Well
- Draws just enough rows/columns to fill canvas + a bit of buffer in the scroll direction.
- Does not try to over-optimize with large overflow calcs, which can backfire.
- Avoids
if logic in the inner loops (conditionals there can slow rendering).
- Keeps matrix transforms and
fillText minimal and effective.
🔬 Further Possible Improvements
Still want more performance? Consider:
✅ 1. Pre-render the background pattern to offscreen canvas:
Store a static pattern (grid of ">") and then scroll/rotate/blit.
This converts many fillText calls into fast drawImage.
✅ 2. Reduce redraw frequency (e.g. only when bgScrollOffset changes)
If background scrolling is slow or infrequent, don't draw it every frame.
✅ 3. Use requestAnimationFrame batching + canvas layer separation
Draw background on a separate canvas (not redrawn every UI update).
✅ Summary
- The previous version got slower likely because its bounds were larger, even if more "direction-aware".
- Optimal loop bounds should be tight but simple, with buffer overflow only where necessary.
- The new version strikes this middle ground: conservative loop area, shift in scroll direction, no heavy math in loops.
Let me know if:
- You want an example using offscreen rendering for performance
- You want to make the scroll continuous and smooth using delta time
- You need pattern-wrapping behavior or real tilemaps
You're very close — great questions 👏