webdevpuneet.com

Asteroids Blaster Game — HTML Canvas Neon Arcade JS

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

CategoryGames

For supporters

Source Code

Want the source code?

Play the game for free. Become a WebDevPuneet supporter to unlock the complete HTML, CSS and JavaScript source code, the exports (HTML, React, Vue, Angular, Tailwind) and Fork.

Play freeSource code: Patreon

Extend with AI

Take This Snippet Further With AI

The AI prompt for this one is for Patreon supporters ($3 a month), along with a site with no ads. Supporters enter the passcode once and it is remembered in this browser.

· Become a supporter

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.

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.

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.