webdevpuneet.com

Asteroids Blaster Game — HTML Canvas Neon Arcade JS

Asteroids Blaster Game · Games · Plain HTML, CSS & JS · Live preview

CategoryGames

About this UI Snippet

Asteroids Blaster — Inertia Physics, Splitting Rocks, UFOs and Combo Scoring on Canvas

Screenshot of the Asteroids Blaster Game snippet rendered live

The original Asteroids is the canonical example of *momentum-based* control: you don't steer the ship, you steer its acceleration. That single idea — rotate to aim a thrust vector, then coast on the velocity you've built up — makes it a perfect demonstration of vector movement, and it maps cleanly onto touch as two rotate buttons plus thrust and fire. This snippet builds a complete, polished version on one HTML5 <canvas>: inertia flight, screen wrapping, glowing procedural rocks that split when shot, UFO saucers that shoot back, a kill-chain score multiplier, lives with respawn invulnerability, wave progression, synthesized sound, pause and a saved high score, all wrapped in a neon arcade look.

Rotate the heading, thrust along it, coast on the velocity

The ship stores a heading angle and a velocity vector (vx, vy) that are deliberately independent. Rotating only changes the angle; THRUST adds acceleration *along the current heading*, and every frame the velocity is multiplied by a drag factor slightly below 1, so the ship slows gradually but never stops on its own. That decoupling of facing from motion is the entire feel of the game — you can drift backwards while firing forwards. Speed is capped by normalising the velocity vector when it exceeds MAX_V, and drag is raised to the power of the frame step so the physics behaves the same at 60Hz and 144Hz.

Toroidal screen wrapping

Ship, bullets, rocks and stars pass through one wrap() function that teleports anything crossing an edge to the opposite side, making the field a torus. Bullets have a limited lifetime, so they expire instead of circling back to hit you.

Rocks that split, UFOs that shoot back

Each rock gets a ring of randomised radii, so no two are the same lumpy shape, and a size class (3, 2 or 1) that sets its colour, speed and points. Shooting one removes it and, unless it is the smallest, spawns two faster pieces, which is the escalating swarm the genre is known for. Every so often a UFO saucer sweeps across on a sine path and fires shots aimed at your ship with a little random error; shooting it is worth 200 points, and its shots or the saucer itself cost a life.

Combo scoring and feedback

Kills chained inside a two-second window raise a multiplier from x2 to x5, shown in the HUD with a pop animation, and floating "+points" text rises from every kill. Each explosion adds particles and an expanding shockwave ring, big hits and deaths shake the screen, and thrust throws cyan and amber exhaust. The glow comes from canvas shadowBlur, with a twinkling parallax starfield that drifts against your velocity and a CSS scanline and vignette layer on top.

Sound without any files

All sound effects (shot, explosion, death, wave jingle, UFO) are synthesized with the Web Audio API: short oscillator sweeps with gain envelopes, and filtered noise bursts for explosions. The audio context is created on the first click, which satisfies autoplay rules, and a mute button (or the M key) saves the choice to localStorage.

Lives, waves, pause and crisp rendering

A collision costs a life, respawns the ship at centre and gives a blinking, shielded invulnerability window. Clearing the field starts the next wave with more rocks and a bonus. P or Esc pause the game, which also pauses automatically when the tab loses focus or is hidden. Logic runs in a fixed 400×400 space but the canvas backing store is scaled by devicePixelRatio, so lines stay sharp on retina screens. For a similar canvas shooter see the Space Blaster arcade game.

What's included

Features

Momentum flight
Independent heading and velocity vectors with acceleration along the heading, frame-rate-independent drag and a speed cap.
Touch and keyboard controls
On-screen rotate, THRUST and FIRE buttons using Pointer Events, plus arrows/WASD/Space, driving one shared input state.
Neon glow rendering
shadowBlur glow, translucent rock fills, a twinkling parallax starfield, scanlines and a vignette, with retina-sharp output via devicePixelRatio.
Splitting rocks and UFOs
Procedural size-classed asteroids that split into faster pieces, plus a saucer enemy that fires aimed shots.
Combo multiplier
Kills chained within two seconds scale points from x2 to x5, with floating score popups.
Juicy effects
Particle bursts, shockwave rings, exhaust sparks, bullet trails and screen shake on big hits and deaths.
Synthesized sound
Web Audio oscillators and filtered noise, created on first click, with a saved mute toggle (M).
Waves, lives, pause and high score
Escalating waves, respawn shield, auto-pause on blur, and a localStorage best score with try/catch guards.

Step by step

How to Use

  1. 1
    LaunchClick "Launch" or press Enter. The ship appears at centre with a shield, a wave banner flashes and wave 1 of large rocks starts drifting. While you are on the title screen the rocks already move behind it.
  2. 2
    Rotate to aimHold ↺ or ↻ (or the arrow keys / A and D) to spin the ship. Rotation only changes the heading, so aim first, then thrust.
  3. 3
    Thrust to build momentumHold THRUST (or ↑ / W) to accelerate along the heading. Release and you keep coasting while drag slowly bleeds speed off, so you can drift one way while facing another.
  4. 4
    Fire and chain killsTap or hold FIRE (or Space). Shots split rocks into faster pieces. Destroying things within two seconds of each other raises the multiplier up to x5.
  5. 5
    Watch for UFOsA green saucer crosses the screen now and then and fires aimed shots. Shoot it for 200 points (multiplied by your combo) before it hits you.
  6. 6
    Pause, mute and beat your bestP or Esc pauses, M toggles sound. A collision costs one of three lives. Your best score is saved in localStorage under asteroids-blaster-best.

Real-world uses

Common Use Cases

Rotational touch-control template
The rotate + thrust + fire layout is a distinct control archetype from a directional D-pad, and a reusable template for any momentum-based touch game such as space shooters or lunar landers.
Teaching vector movement and inertia
Decoupling heading from velocity, accelerating along a vector, applying drag and capping speed are the foundations of 2D physics movement, shown here in compact, readable form.
Starting point for a fuller space game
The vector ship, wrap() and splitting rocks generalise to shields, power-ups, hyperspace jumps or boss fights without touching the delta-time loop. Compare the approach with the Space Blaster arcade game.
Instantly playable arcade demo
A self-contained shooter with no images or audio files starts immediately, a strong embeddable demo for a games portal, blog or landing page.
Interactive 404 or loading filler
With no network dependency it makes an engaging distraction on an error or loading screen. For a calmer option see the Breakout brick game.
Canvas effects reference
Glow with shadowBlur, shockwave rings, particle systems, screen shake, parallax stars and devicePixelRatio scaling are all reusable in any 2D canvas scene.

Got questions?

Frequently Asked Questions

Asteroids is momentum-based: the ship stores a velocity vector that persists between frames. Thrusting only adds acceleration along the heading; when you release, the velocity remains and a drag factor just below 1 slows it gradually. That inertia is the defining feel of the game.

Every moving object passes through a single wrap() function that checks whether it has crossed an edge and, if so, adds or subtracts the canvas width or height. Applying it to the ship, bullets, rocks and stars makes the field a torus. Bullets expire after a limited lifetime so they cannot circle back forever.

Each kill checks a countdown. If it is still running, the combo count goes up (to a maximum of 5) and the countdown restarts at two seconds; otherwise it starts at 1. Points are the base value times the combo count. Losing a life resets it.

The Web Audio API generates it: an oscillator with a frequency sweep and a gain envelope for shots, deaths and jingles, and a buffer of fading random noise through a low-pass filter for explosions. The AudioContext is created on the first click to satisfy browser autoplay rules, and the mute state is saved in localStorage.

The game logic uses a fixed 400 by 400 space, but the canvas backing store is multiplied by the device pixel ratio (capped at 2) and the context is scaled to match. Lines then stay sharp on high-density screens without changing any game coordinates.

Yes. The best score is written to localStorage under asteroids-blaster-best and read on load. Reads and writes are wrapped in try/catch so the game still runs in sandboxed or private contexts where storage access can throw.

Render the canvas and overlays in a component, create the context in a mount effect and run the requestAnimationFrame loop there, storing game state in refs rather than React state. Cancel the loop and remove the keyboard listeners in the cleanup function. Use the export buttons on this page for the markup and styles.

Copy & paste

Source Code

<div class="game-card">
  <div class="game-header">
    <div class="game-title">
      <span class="logo" aria-hidden="true"><svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linejoin="round"><path d="M21 12 4 20l4-8-4-8z"/></svg></span>
      <div>
        <h2>Asteroids Blaster</h2>
        <p class="tagline">Neon vector arcade</p>
      </div>
    </div>
    <div class="head-right">
      <span class="badge">Wave <b id="wave">1</b></span>
      <span class="badge">Best <b id="best-score">0</b></span>
      <button class="icon-btn" id="btn-sound" type="button" aria-pressed="true" aria-label="Sound on" title="Sound (M)">🔊</button>
      <button class="icon-btn" id="btn-pause" type="button" aria-label="Pause" title="Pause (P)">❚❚</button>
    </div>
  </div>

  <div class="canvas-wrap">
    <canvas id="game-canvas" width="400" height="400" aria-label="Asteroids game canvas"></canvas>
    <div class="hud" aria-live="off">
      <span class="hud-score" id="hud-score">0</span>
      <span class="hud-combo" id="hud-combo"></span>
      <span class="lives" id="hud-lives"></span>
    </div>
    <div class="wave-banner" id="wave-banner" aria-hidden="true"></div>

    <div class="overlay" id="start-overlay">
      <div class="overlay-card">
        <p class="overlay-kicker">Arcade classic</p>
        <p class="overlay-title">Asteroids <span>Blaster</span></p>
        <p class="overlay-sub">Spin, thrust and shoot. Rocks split into faster pieces, UFOs shoot back, and chaining kills multiplies your score.</p>
        <ul class="keys"><li><kbd>←</kbd><kbd>→</kbd> rotate</li><li><kbd>↑</kbd> thrust</li><li><kbd>Space</kbd> fire</li><li><kbd>P</kbd> pause</li></ul>
        <button class="btn btn-primary" id="btn-start" type="button">Launch</button>
      </div>
    </div>
    <div class="overlay hidden" id="pause-overlay">
      <div class="overlay-card">
        <p class="overlay-title">Paused</p>
        <button class="btn btn-primary" id="btn-resume" type="button">Resume</button>
      </div>
    </div>
    <div class="overlay hidden" id="gameover-overlay">
      <div class="overlay-card">
        <p class="overlay-title over">Wrecked</p>
        <p class="overlay-score" id="final-score">0</p>
        <p class="overlay-sub" id="final-detail">Wave 1</p>
        <p class="overlay-best" id="best-msg"></p>
        <button class="btn btn-primary" id="btn-retry" type="button">Relaunch</button>
      </div>
    </div>
  </div>

  <div class="controls">
    <div class="dpad">
      <button class="ctrl-btn" id="btn-left" type="button" aria-label="Rotate left">↺</button>
      <button class="ctrl-btn" id="btn-right" type="button" aria-label="Rotate right">↻</button>
    </div>
    <div class="actions">
      <button class="act-btn thrust" id="btn-thrust" type="button" aria-label="Thrust">THRUST</button>
      <button class="act-btn fire" id="btn-fire" type="button" aria-label="Fire">FIRE</button>
    </div>
  </div>
  <p class="hint-text">Keys: ← → rotate · ↑ thrust · Space fire · P pause · M sound</p>
</div>

Extend with AI

Take This Snippet Further With AI

Paste this snippet's HTML, CSS and JS into an AI assistant like Claude and ask it to explain how the independent heading and velocity vectors, drag raised to the frame step, and the shared wrap() function combine into Asteroids-style momentum flight, or how the combo window and the UFO's aimed shots are timed. It is a strong base to extend: ask for a hyperspace teleport button, a shield or extra-life pickup, shot power-ups (spread, rapid fire), a boss UFO every fifth wave, or an online leaderboard. You could also ask it to add gamepad support, tune the difficulty curve per wave, or port the loop into a React component using useRef and useEffect. Treat it as a working prototype to question and rebuild rather than a finished game.

Prompt to recreate it

Copy this into your AI assistant of choice to build the effect from scratch, or as a jumping-off point for your own variant:

text
Build a polished, mobile-friendly Asteroids-style vector shooter on an HTML5 canvas, as ONE self-contained HTML file (inline CSS and JS, no frameworks, no asset files). Dark neon arcade look.

GAME CORE
- A ship with momentum: an independent heading angle and velocity vector. Rotate changes only the angle, thrust accelerates along the heading, drag (raised to the frame step) bleeds speed, and speed is capped. Scale everything by delta time. Wrap the ship, bullets, rocks and stars around the edges with one shared wrap function; bullets expire after about 55 frames.
- Procedural lumpy asteroids with three size classes (different colours, speeds and points). A hit splits a rock into two faster smaller ones; rocks get slightly faster each wave.
- A UFO saucer that appears every 15 to 25 seconds, sweeps across on a sine path and fires shots aimed at the ship with random error. Shooting it gives 200 points; its shots or contact cost a life.
- 3 lives, a blinking shielded invulnerability period after respawn, wave progression with more rocks (capped) and a wave-clear bonus, and a combo multiplier (x2 to x5) for kills chained within 2 seconds that resets on death.
- High score saved in localStorage with try/catch.

VISUALS
- Logic in a 400x400 space; scale the canvas backing store by devicePixelRatio (max 2) for sharp lines. Glow with shadowBlur, translucent rock fills, twinkling parallax starfield that drifts against the ship's velocity, bullet trails, thrust flame plus exhaust particles, particle bursts, expanding shockwave rings, floating "+points" popups, and screen shake on deaths and big rocks (disabled for prefers-reduced-motion). A CSS scanline and vignette overlay on the canvas.
- A card UI: header with logo, title, Wave and Best badges, sound and pause buttons; an in-canvas HUD (score, combo, lives as small ship icons); a "WAVE N" banner animation; start, pause and game-over overlays (game over shows score, wave, rocks destroyed and a new-high-score message). While idle or game over, rocks keep drifting behind the overlay.

CONTROLS AND AUDIO
- On-screen rotate-left, rotate-right, THRUST and FIRE buttons using Pointer Events with press-and-hold (release on pointerup/cancel/leave), plus keyboard (arrows or WASD, Space), Enter to start, P or Esc to pause, M to mute. One shared input-state object read once per frame. Auto-pause on window blur and when the tab is hidden.
- Sound synthesized with the Web Audio API (no files): square sweep for shots, filtered noise for explosions, sawtooth drop for death, triangle jingle for waves, a short tone for the UFO. Create the AudioContext on the first user click; saved mute toggle.

Use a single permanent requestAnimationFrame loop that simulates only while playing. Return only the finished single HTML file.

Want to tighten it up first? Run this prompt through the AI Prompt Studio to score it across 8 quality dimensions, catch anti-patterns, and tune the wording for Claude, ChatGPT, or Gemini before you paste it in.