Single-File Canvas Tower Defense: Architecture and Performance Practices
Learn how to structure a complete tower defense game in a single HTML file using vanilla JavaScript and Canvas. This article covers cached pathfinding, combat rules, object pooling, fixed-step updates, responsive controls, and an acceptance checklist for validating performance and gameplay consistency.
1. The Challenge: A Complete Game in One HTML File
For prototyping, teaching, and lightweight delivery, a game that runs from a single HTML file has clear advantages: no build tools, no dependency installation, easy distribution, and a double-click launch. But fitting pathfinding, real-time combat, particle effects, UI interactions, and saved data into one file quickly introduces engineering challenges. Code organization, rendering performance, state management, and testability can all become bottlenecks.
This article uses a representative tower defense specification:
- A 15 × 10 grid with an S-shaped path
- Three tower types and three standard enemy types
- 20 waves, including bosses
- Vanilla JavaScript and Canvas
- A 60 fps target
- Object pooling
- A dark sci-fi interface
- Synthesized sound effects and touch support
The implementation approach spans architecture, algorithms, rendering, and acceptance testing, with practical code snippets.
Specifications like this also serve as useful benchmarks for AI coding tools. Detailed requirements expose differences in generated code, particularly around edge cases, state consistency, and playability. Section 8 provides a checklist for evaluating those areas.
2. Architecture: One File Does Not Mean One Function
A single file is a distribution format, not a reason to abandon internal structure. Organize the code into data, logic, rendering, and input layers within one <script> block. A namespace or aggregate object helps avoid polluting the global scope:
const Game = {config: { cols: 15, rows: 10, cell: 48 },state: { gold: 500, lives: 20, wave: 0, speed: 1 },systems: { path: null, towers: [], enemies: [], bullets: null, particles: null },loop: null};
Three principles keep the design manageable:
- Separate configuration from runtime state. Store tower prices, damage, range, enemy health, and similar values in
config. This makes balancing easier and supports derived rules such as three upgrade levels with a 40% increase per level. - Define clear system boundaries. Pathfinding produces waypoints; towers select targets and fire; projectiles handle movement and hits; particles handle visuals. Systems should communicate through events or state queries rather than directly modifying one another’s fields.
- Use one main-loop entry point. Drive updates from a
requestAnimationFramecallback. A fixed-step accumulator controls simulation updates, while rendering follows the actual frame rate. This prevents gameplay from running faster on high-refresh-rate displays.
3. Maps and Pathfinding: Precompute Static Routes
The specification asks enemies to follow a predefined S-shaped route while also requiring A or a similar pathfinding algorithm. These requirements are compatible: *when the map is static, calculate the route once.
Define the S-shaped route in grid coordinates. At startup, use A* to check connectivity, allowing movement only through path cells, then cache the resulting waypoint array. This provides pathfinding capability without repeating searches for every enemy on every frame.
The core search can be expressed as follows. This excerpt assumes supporting helpers for keys, scores, neighbors, walkability, and route reconstruction:
function aStar(grid, start, goal) {const open = [start];const came = new Map();const g = new Map([[key(start), 0]]);while (open.length) {open.sort((a, b) => f(a) - f(b));const cur = open.shift();if (cur.x === goal.x && cur.y === goal.y) return rebuild(came, cur);for (const n of neighbors(cur)) {if (!walkable(grid, n)) continue;const ng = g.get(key(cur)) + 1;if (ng < (g.get(key(n)) ?? Infinity)) {came.set(key(n), cur);g.set(key(n), ng);if (!open.some(p => p.x === n.x && p.y === n.y)) open.push(n);}}}return [];}
Enemy movement then becomes interpolation along the cached waypoints. Track the current destination index and distance traveled, advance by speed * dt, and move to the next waypoint when a segment is completed. This keeps movement smooth and naturally supports different enemy speeds.
Define flying-enemy behavior explicitly. If flying units travel in a straight line, they need separate movement logic. If they follow the ground route, only their targeting rules need to differ. Straight-line flight is generally more intuitive for this design, but it adds state branches that should be documented.
4. Combat Balance: Tower and Enemy Matchups
Playable tower defense depends on meaningful strengths and counters. Start with base values and derive upgraded attributes using a consistent formula.
| Tower type | Cost | Base damage | Fire rate (shots/sec) | Range (cells) | Special behavior |
|---|---|---|---|---|---|
| Machine gun | 100 | Low | High | Short | Consistent single-target damage |
| Rocket | 200 | High | Low | Long | Area damage; can attack flying enemies |
| Electromagnetic | 150 | Medium | Medium | Medium | Slows enemies by 50% for 2 seconds |
Use the upgrade formula:
value * (1 + 0.4 * (level - 1))
Cap towers at level 3. Selling returns 60% of the total amount invested. Record that investment at purchase and after each upgrade; refunding only a percentage of the base price would make the economy inconsistent.
Enemy characteristics are:
- Standard enemy: 100 health, medium speed.
- Tank: 400 health, slow movement, 30% damage reduction against rockets.
- Flying enemy: 80 health, fast movement, targetable only by rocket towers.
- Boss: Appears every five waves, with ten times the health of a standard enemy in the same wave.
Two implementation details deserve particular attention.
First, apply damage reduction centrally during damage resolution rather than hard-coding it into tower attack logic. Second, clamp health to zero. Negative health can produce negative-width or reversed health bars.
Enemy.prototype.takeDamage = function (amount, sourceType) {if (this.type === 'tank' && sourceType === 'rocket') amount *= 0.7;this.hp = Math.max(0, this.hp - amount);if (this.hp === 0) this.die();};
Offer two targeting modes: nearest target, to reduce time spent without a useful target, and lowest health, to clear weakened enemies and reduce overkill. A single pass through the enemy list is sufficient:
function pickTarget(tower, enemies, mode) {let best = null, bestScore = Infinity;for (const e of enemies) {if (!inRange(tower, e) || !canHit(tower, e)) continue;const score = mode === 'nearest' ? dist2(tower, e) : e.hp;if (score < bestScore) { bestScore = score; best = e; }}return best;}
5. Rendering and Performance: Design for 60 fps
Consistent Canvas performance is not just about drawing faster. It is about drawing less, allocating fewer objects, and avoiding unnecessary layout work.
Layered Rendering
Draw the static map—grid, route, and decorations—to an offscreen canvas. Rebuild it only when dimensions change. Each frame, clear the visible canvas, draw the cached background, and render dynamic elements: towers, enemies, projectiles, particles, and UI overlays.
This replaces repeated static drawing with a single drawImage call.
Object Pooling
Projectiles and particles are created and discarded frequently, making them strong candidates for pooling. The basic lifecycle is acquire, use, reset, and release:
function createPool(factory, size) {const free = Array.from({ length: size }, factory);return {get() { return free.pop() || factory(); },put(obj) { obj.active = false; free.push(obj); }};}
This minimal pool only marks returned objects inactive. The caller must reset their remaining fields, including velocity, lifetime, and color, before reuse. Incomplete resets can produce ghost particles or projectiles with incorrect trajectories.
Fixed-Step Updates and Speed Controls
For 1×, 2×, and 3× speed modes, avoid simply increasing the timestep passed to the simulation. Larger steps increase the risk of projectiles skipping collision checks.
Instead, accumulate more simulation time and run additional updates at the same fixed timestep:
let acc = 0;const STEP = 1 / 60;function frame(now) {const raw = Math.min((now - last) / 1000, 0.1);last = now;acc += raw * Game.state.speed;while (acc >= STEP) { update(STEP); acc -= STEP; }render();requestAnimationFrame(frame);}
Collision Detection
Compare the squared distance between a projectile and an enemy’s center with the squared collision radius. This avoids square-root calculations.
For a controlled number of enemies, spatial partitioning is unnecessary. If later waves become densely populated, grid buckets can be added to accelerate collision queries.
FPS Display
Use a moving average rather than an instantaneous FPS reading. A smoother display is easier to read and less distracting.
6. Effects: Strong Visual Feedback at Low Cost
Particles, projectile trails, and screen shake provide effective feedback with relatively little complexity. Keep their counts bounded and manage their lifetimes carefully.
- Projectile trails: Store the launch position, target reference, and flight progress. Interpolate the position using
tand apply damage only on impact. Define target invalidation behavior explicitly so an enemy dying in flight does not break damage handling. - Explosion particles: Generate 8–12 particles on rocket impact, with randomized velocity, gravity, and fading opacity. Cap the total particle count—for example, at 300—and reuse the oldest particles when the limit is reached.
- Electromagnetic pulses: Draw an expanding ring around the tower. Use
globalCompositeOperation = 'lighter'for a low-cost additive glow. - Death effects: Spawn short-lived debris particles and represent floating gold rewards as lightweight text particles.
For audio, use the Web Audio API to synthesize short effects: a high-frequency square wave for firing, noise with a low-pass filter for explosions, and two ascending notes for gold rewards. Create audio nodes after the first user interaction to avoid browser autoplay restrictions.
7. UI and Input: Sci-Fi Styling and Mobile Support
A dark blue-black background with cyan and magenta accents creates a sci-fi look. Use translucent outlines and shadowBlur for glow, but reserve blur for important elements such as selection indicators, bosses, and UI highlights. Applying it broadly can be expensive.
A three-part layout works well:
- Top status bar: Wave, gold, lives, and FPS
- Right panel: Tower selection, upgrades, selling, and targeting mode
- Bottom controls: Start wave and change speed
Combining DOM UI with Canvas is a practical choice. HTML makes layout and accessibility easier, while Canvas handles the game world.
When a tower is selected, draw its attack radius with two strokes: one wide, translucent stroke and one narrow, bright stroke. This produces a glow-like effect without a complex rendering pipeline.
For mobile support:
- Scale the Canvas backing buffer using
devicePixelRatioto keep graphics sharp on high-density screens. - Use
pointerdownandpointermoveto handle mouse and touch input through the same event model. - Convert pointer positions back into grid coordinates for placement and selection.
- On narrow screens, turn the side panel into a bottom drawer or collapsible panel so the map remains visible.
- Keep button touch targets at least 44 × 44 CSS pixels.
8. Acceptance Testing: Catching Bugs That “Look Fine”
Both generated and handwritten code often fail at state boundaries rather than in the main gameplay flow. Use the following checklist for self-testing:
- Placement validation: Reject path cells, occupied cells, insufficient funds, and out-of-bounds positions with clear feedback. Selecting an existing tower must not prevent subsequent building on valid empty cells.
- Numeric limits: Health must not fall below zero; gold must not become negative; tower levels must not exceed 3; waves must not exceed 20.
- Economic consistency: Purchase costs, upgrade investment, and sale refunds must agree. Repeated buying and selling must not generate profit.
- Invalid targets: If a target dies while a projectile is in flight, the projectile should safely dissipate without accessing a recycled object.
- Pool resets: Reset all object fields before reuse. Active object counts should not keep growing during extended play.
- Speed changes: At 3× speed, check for missed collisions and stuttering caused by accumulated simulation work.
- Pause and restart: During an active wave, test switching browser tabs and restarting. Timers, particle pools, and audio nodes must be paused, reset, or cleaned up appropriately.
- Saved data: Store the high score in local storage. If reading fails, fall back to a default value without an uncaught exception.
In team workflows, turn suitable checklist items into automated smoke tests and static checks, and run them in the commit or continuous integration pipeline to catch basic errors early.
For development that relies heavily on code generation, human playtesting remains essential. Passing a syntax check does not mean the game passes gameplay acceptance.
9. Conclusion
A single-file Canvas tower defense game may look like a small HTML exercise, but it tests four substantial engineering skills: layered design, algorithm selection, rendering budgets, and edge-case handling.
Separating static and dynamic rendering, precomputing routes, pooling frequently used objects, and using fixed-step simulation provide a strong foundation for a zero-dependency game targeting stable 60 fps. A state-focused acceptance checklist then helps verify that the result is not merely runnable, but playable and maintainable.
The same structure also leaves room for more complex mechanics, including multiple routes, tower merging, and skill systems.
