Advertiser Disclosure

How to Make a Game in JavaScript

Build a complete browser game in plain JavaScript with no libraries: a game loop, keyboard and touch controls, collisions, scoring, and a saved best score.

Illustration of the Comet Dodge game running in a browser window, a green ship dodging orange comets and catching a yellow star, labeled with the update and draw steps of the game loop

By Michael Stromberg, Hack Reactor graduate (2016) · Last verified November 30, 2026

In this tutorial you’ll make a complete game in JavaScript, with no libraries and no game engine: just an HTML page, a <canvas>, and about 200 lines of code. The game is called Comet Dodge. You steer a ship along the bottom of the screen, dodge falling comets, and catch stars for bonus points. It speeds up as you survive, remembers your best score, and works with a keyboard or a touchscreen.

Along the way you’ll learn the ideas every game is built on, whether it runs in a browser or in an engine like Godot or Unity: a game loop, game state, input, movement over time, collision detection, and a way to win or lose.

Screenshot of Comet Dodge, the game built in this tutorial: a green ship at the bottom of a dark canvas, orange comets falling, a yellow star, and the score and best score at the top. You steer with the arrow keys or a finger, dodge comets that fall faster over time, catch stars for 50 points, and your best score is saved in the browser

The short answer: a JavaScript game is a loop. About 60 times a second, the browser calls your function; you update the game (move things, check for collisions, add to the score) and then draw the new frame on a canvas. Everything else is details: what’s on screen, how the player controls it, and when the game ends.

What you need

  • A web browser such as Chrome, Firefox, Safari, or Edge.
  • A code editor. Any will do; VS Code is free and popular.
  • Basic JavaScript: variables, functions, arrays, objects, and if statements. If those feel shaky, work through our 10 JavaScript practice problems first.

There’s nothing to install. Make a folder called comet-dodge with two empty files in it: index.html and game.js.

How a browser game works

A web page normally sits still until you click something. A game is different: it redraws itself constantly, even when you do nothing, because comets keep falling. That’s the job of the game loop.

One trip around the game loop, about 60 times a second: the browser calls loop(now) through requestAnimationFrame; the loop measures dt, the seconds since the last frame; update(dt) moves the ship and comets, spawns new ones, checks collisions and adds to the score; draw() clears the canvas and paints the frame; then requestAnimationFrame(loop) asks for the next frame. Moving things by speed times dt keeps the game the same speed on 60 Hz and 120 Hz screens

The browser gives us exactly the tool we need: requestAnimationFrame(callback) asks it to call your function just before it draws the next frame. That usually matches the screen’s refresh rate, most often 60 times a second, and it pauses when the tab is hidden, so the game doesn’t burn battery in the background. Each time it runs, the loop does two things:

  • Update: change the game’s state. Move the ship and the comets, check whether anything touched, add to the score.
  • Draw: wipe the canvas and paint everything where it is now.

Because screens refresh at different rates (60, 120, even 144 times a second), we never move things “5 pixels per frame.” We move them by speed × time: the loop measures how many seconds passed since the last frame, called the delta time or dt, and every movement is multiplied by it. That way the game runs at the same speed on every screen.

Step 1: Create the page

Put this in index.html. The <canvas> is the game’s drawing surface: 480 pixels wide and 640 tall. The CSS centers it and shrinks it to fit small screens.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Comet Dodge</title>
  <style>
    body {
      margin: 0;
      min-height: 100vh;
      display: flex;
      align-items: center;
      justify-content: center;
      background: #0b0b1a;
    }
    canvas {
      max-width: 100%;
      max-height: 100vh;
      background: #14142b;
    }
  </style>
</head>
<body>
  <canvas id="game" width="480" height="640"></canvas>
  <script src="game.js"></script>
</body>
</html>

Step 2: Set up the canvas and the game state

Now open game.js. Everything in this tutorial goes into this one file, block by block, in order. The first block grabs the canvas and its 2D drawing context, ctx, which has all the drawing methods, and turns off the browser’s touch scrolling on the canvas, so dragging a finger across the game on a phone steers the ship instead of scrolling the page. Then it creates the game state: every value that describes the game at this moment.

// ---- Setup ----
const canvas = document.getElementById("game");
const ctx = canvas.getContext("2d");
const W = canvas.width;
const H = canvas.height;
canvas.style.touchAction = "none"; // stop the page scrolling while you play on a phone

const ship = { x: W / 2, y: H - 60, radius: 16, speed: 320 };
let comets = [];
let stars = [];
let score = 0;
let best = Number(localStorage.getItem("cometDodgeBest")) || 0;
let state = "ready"; // "ready", "playing" or "over"
let elapsed = 0; // seconds since this round started
let cometTimer = 0;
let starTimer = 0;

The ship is a plain object with a position, a size, and a speed in pixels per second. Comets and stars will be objects with the same kind of properties, kept in arrays. state says which screen we’re on: the start screen, playing, or game over. best reads the best score saved in the browser by localStorage, which we’ll write to at the end of each game. localStorage stores text, so Number() turns it back into a number, and || 0 covers the first visit, when nothing is saved yet.

Step 3: Draw the game

Next, a draw() function that paints one frame. Canvas drawing works like a painter: you choose a color with fillStyle, describe a shape, and fill it. Whatever you draw last ends up on top, which is how the dark “Game over” panel covers the game behind it.

// ---- Draw ----
function draw() {
  ctx.clearRect(0, 0, W, H);

  // The ship: a triangle pointing up
  ctx.fillStyle = "#7fe3b0";
  ctx.beginPath();
  ctx.moveTo(ship.x, ship.y - ship.radius);
  ctx.lineTo(ship.x - ship.radius, ship.y + ship.radius);
  ctx.lineTo(ship.x + ship.radius, ship.y + ship.radius);
  ctx.closePath();
  ctx.fill();

  ctx.fillStyle = "#ff7a59";
  for (const comet of comets) circle(comet);

  ctx.fillStyle = "#ffd84d";
  for (const star of stars) circle(star);

  ctx.fillStyle = "#ffffff";
  ctx.font = "20px sans-serif";
  ctx.textAlign = "left";
  ctx.fillText(`Score: ${Math.floor(score)}`, 16, 32);
  ctx.textAlign = "right";
  ctx.fillText(`Best: ${best}`, W - 16, 32);

  if (state === "ready") message("Comet Dodge", "Press Space or tap to start");
  if (state === "over") message("Game over", "Press Space or tap to play again");
}

function circle(thing) {
  ctx.beginPath();
  ctx.arc(thing.x, thing.y, thing.radius, 0, Math.PI * 2);
  ctx.fill();
}

function message(title, hint) {
  ctx.fillStyle = "rgba(0, 0, 0, 0.6)";
  ctx.fillRect(0, 0, W, H);
  ctx.fillStyle = "#ffffff";
  ctx.textAlign = "center";
  ctx.font = "bold 40px sans-serif";
  ctx.fillText(title, W / 2, H / 2 - 10);
  ctx.font = "18px sans-serif";
  ctx.fillText(hint, W / 2, H / 2 + 30);
}

The ship is a triangle drawn with a path: moveTo the tip, lineTo the two bottom corners, then fill(). Comets and stars are circles, drawn with arc() from 0 to Math.PI * 2, a full turn. Note that the canvas’s y-axis points down: y = 0 is the top edge, so things fall by adding to y.

Check your work: add the line draw(); at the very bottom of game.js and open index.html in your browser. You should see the start screen with the ship at the bottom. Delete that line once it works; the game loop will call draw() for us.

Step 4: Handle keyboard and touch input

Input handlers don’t move the ship themselves. They just record what the player is doing, and the update step reads that record every frame. This keeps movement smooth: holding an arrow key moves the ship steadily instead of in the jerky bursts of a key’s auto-repeat.

// ---- Input ----
const keys = {};
let pointerX = null; // where a finger or mouse is holding, or null

window.addEventListener("keydown", (event) => {
  keys[event.key] = true;
  if ([" ", "ArrowLeft", "ArrowRight"].includes(event.key)) event.preventDefault();
  if ((event.key === " " || event.key === "Enter") && state !== "playing") start();
});

window.addEventListener("keyup", (event) => {
  keys[event.key] = false;
});

canvas.addEventListener("pointerdown", (event) => {
  if (state !== "playing") start();
  pointerX = canvasX(event);
});

canvas.addEventListener("pointermove", (event) => {
  if (pointerX !== null) pointerX = canvasX(event);
});

window.addEventListener("pointerup", () => {
  pointerX = null;
});

// Converts a mouse or touch position to canvas coordinates,
// since CSS may show the canvas smaller or larger than 480 pixels.
function canvasX(event) {
  const rect = canvas.getBoundingClientRect();
  return ((event.clientX - rect.left) / rect.width) * W;
}

keys remembers which keys are held down right now: keys["ArrowLeft"] is true from the moment you press the key until you let go. For touchscreens and mice we use pointer events, which handle both with the same code. While a finger is down, pointerX holds its position, and the ship will steer toward it. preventDefault() stops the arrow keys and Space from scrolling the page while you play.

One subtle step: CSS may display the canvas at a different size than its 480 pixels, for example on a narrow phone. canvasX() converts the finger’s position on the page into the canvas’s own coordinates, so steering lines up on any screen.

Step 5: Update the game: movement, comets, and collisions

This is the heart of the game. update(dt) runs once per frame and moves the world forward by dt seconds.

// ---- Update ----
function update(dt) {
  if (state !== "playing") return;
  elapsed += dt;
  score += dt * 10; // 10 points for every second you survive

  moveShip(dt);
  spawn(dt);

  for (const comet of comets) comet.y += comet.speed * dt;
  for (const star of stars) star.y += star.speed * dt;

  for (const comet of comets) {
    if (touching(ship, comet)) gameOver();
  }
  for (const star of stars) {
    if (touching(ship, star)) {
      star.collected = true;
      score += 50;
    }
  }

  // Forget anything that fell off the bottom or was collected
  comets = comets.filter((comet) => comet.y - comet.radius < H);
  stars = stars.filter((star) => !star.collected && star.y - star.radius < H);
}

function moveShip(dt) {
  let direction = 0;
  if (keys["ArrowLeft"] || keys["a"]) direction -= 1;
  if (keys["ArrowRight"] || keys["d"]) direction += 1;
  if (pointerX !== null && Math.abs(pointerX - ship.x) > 4) {
    direction = Math.sign(pointerX - ship.x);
  }
  ship.x += direction * ship.speed * dt;
  // Keep the ship on the screen
  ship.x = Math.max(ship.radius, Math.min(W - ship.radius, ship.x));
}

function spawn(dt) {
  // Difficulty climbs from 1 to 3 over the first minute
  const difficulty = Math.min(3, 1 + elapsed / 30);

  cometTimer -= dt;
  if (cometTimer <= 0) {
    comets.push(makeFaller(random(12, 26), random(150, 230) * difficulty));
    cometTimer = 0.9 / difficulty;
  }

  starTimer -= dt;
  if (starTimer <= 0) {
    stars.push(makeFaller(10, 160));
    starTimer = random(2, 4);
  }
}

function makeFaller(radius, speed) {
  return { x: random(radius, W - radius), y: -radius, radius, speed };
}

function random(min, max) {
  return min + Math.random() * (max - min);
}

// Two circles touch when the distance between their centers
// is less than their two radiuses added together.
function touching(a, b) {
  return Math.hypot(a.x - b.x, a.y - b.y) < a.radius + b.radius;
}

Moving the ship

moveShip() turns input into a direction of -1 (left), 0, or 1 (right), then moves the ship by direction × speed × dt. At 320 pixels per second, holding a key for half a second moves the ship 160 pixels, no matter how fast the screen refreshes. The last line clamps the ship’s x so it can’t leave the screen.

Spawning comets and stars

spawn() uses timers that count down by dt. When one reaches zero, a new comet appears above the top edge at a random x, and the timer resets. The difficulty value climbs from 1 to 3 over the first minute, and it does two jobs at once: comets fall faster, and they arrive more often. That single number is what makes the game get harder the longer you survive.

Collision detection

To check whether two things touch, we treat both as circles. Two circles overlap when the distance between their centers is less than their two radiuses added together, and Math.hypot() gives us that distance. The ship is really a triangle, so its circle is a slightly generous “hitbox”; most games use simple shapes like this for collisions, because exact shapes are slower and rarely feel fairer.

Finally, filter() throws away comets that fell off the bottom and stars you caught. Without that cleanup, the arrays would grow forever and the game would slowly get slower.

Step 6: Start, game over, and the best score

Two small functions switch between the screens. start() resets the game state for a new round, and gameOver() ends it and saves the best score.

// ---- Start and game over ----
function start() {
  comets = [];
  stars = [];
  score = 0;
  elapsed = 0;
  cometTimer = 0;
  starTimer = 2;
  ship.x = W / 2;
  state = "playing";
}

function gameOver() {
  state = "over";
  best = Math.max(best, Math.floor(score));
  localStorage.setItem("cometDodgeBest", best);
}

localStorage.setItem() saves the best score in the browser, so it’s still there after you close the tab. Because update() does nothing unless state is "playing", the world freezes as soon as you’re hit, and draw() shows the “Game over” panel on top of it.

Step 7: Start the game loop and play

The last block brings everything to life. Add it to the bottom of game.js:

// ---- Game loop ----
let last = performance.now();

function loop(now) {
  // Seconds since the last frame, capped so a paused tab doesn't jump ahead
  const dt = Math.min((now - last) / 1000, 0.05);
  last = now;
  update(dt);
  draw();
  requestAnimationFrame(loop);
}

requestAnimationFrame(loop);

requestAnimationFrame passes your function a timestamp in milliseconds. Subtracting the previous timestamp and dividing by 1,000 gives dt in seconds. The Math.min(…, 0.05) cap matters more than it looks: if you switch tabs, the loop pauses, and when you come back the first dt could be many seconds long. Without the cap, every comet would jump the whole way down the screen at once.

Save, reload index.html, and press Space or tap the game. You have a working game.

Common problems

What you seeLikely causeFix
A blank pageThe browser can’t find game.jsKeep both files in the same folder and check the file name in the <script> tag
Nothing moves after pressing SpaceThe game loop from Step 7 is missingAdd it at the bottom of game.js, and check the browser console (F12) for errors
update is not defined in the consoleA block is missingCompare your file against the steps in order
The game runs faster on some screensSomething moves without multiplying by dtUse speed × dt for every movement
The page scrolls while playing on a phoneThe touch-scrolling line is missingKeep canvas.style.touchAction = "none" from Step 2
The best score resetsPrivate windows clear saved data when you close themPlay in a normal window

Make it your own

The fastest way to learn game programming is to change one thing and see what happens. Some ideas, roughly from easiest to hardest:

  • Tune the feel: change the ship’s speed, the comet speeds, or how fast difficulty grows. Small numbers make a big difference.
  • Add a pause: a new "paused" state, toggled with the P key.
  • Use images: load a picture with new Image() and draw it with ctx.drawImage() instead of shapes.
  • Add sound: play a short clip with new Audio("catch.mp3").play() when you catch a star.
  • Add lives or shields: instead of ending the game, take away a life and make the ship blink for a second.
  • Let the ship shoot: lasers are just another array of moving circles, plus one more collision check.

For your next project, you might also try building an AI chatbot in JavaScript, which covers the server side of JavaScript.

When to move to a game engine

Plain JavaScript is a great way to learn, and it’s enough for small games like this one. As games grow, you’ll want things you’d otherwise build yourself: physics, animation, sound, level editors, and exporting to phones and consoles. That’s what frameworks and engines give you.

  • Stay in the browser with Phaser: a free, open-source framework for 2D HTML5 games, so your JavaScript skills carry over directly.
  • Move to a full engine: Godot, Unity, and Unreal Engine each have an editor, physics, and export to desktop and mobile. Our Unity vs. Unreal vs. Godot comparison helps you pick one.

If you’re leaning toward Godot, a free, open-source engine whose scripting language reads a lot like Python, GameDev.tv has a free two-hour Get Started with Godot course, and our best Godot courses guide covers what to take after it. For everything else, start at our game development hub.

*We may earn a commission when you click through these links.

From Michael, Hack Reactor ’16: Small games are one of the best ways to practice programming, because you can see every bug. If the comet goes through the ship, your collision check is wrong; you don’t need a test suite to tell you. When you finish this one, make a second game from scratch without looking back at the code. Whatever you have to look up is exactly what you haven’t learned yet.

JavaScript Game FAQ

Can you make a game with just JavaScript?

Yes. Every modern browser can run a game written in plain JavaScript using the <canvas> element, with no libraries or installs. The game in this tutorial is about 200 lines of JavaScript plus a short HTML page.

Is JavaScript good for making games?

It’s very good for learning and for 2D browser games, which anyone can play from a link. For large 3D games or console releases, most developers use an engine such as Unity (C#), Unreal (C++ and Blueprints), or Godot (GDScript or C#).

What is a game loop?

A function that runs over and over, usually once per screen refresh. Each time, it updates the game’s state (positions, collisions, score) and then draws the new frame. In the browser you build it with requestAnimationFrame.

Why multiply by delta time?

Screens refresh at different rates, so the loop runs a different number of times per second on different devices. Multiplying every movement by the seconds since the last frame makes the game run at the same speed everywhere.

Should I use canvas or HTML elements for a game?

Canvas is the usual choice for action games, because you redraw the whole scene every frame. Regular HTML elements work well for slower games like quizzes, card games, or puzzles, where only a few things change at a time.

What should I learn after this?

Add features to this game first. Then try a framework like Phaser to stay in JavaScript, or move to an engine such as Godot, Unity, or Unreal. Our game development hub compares engines and courses.

Advertiser disclosure: Some companies on this page are affiliate partners. We earn a commission when you buy through our links, at no extra cost to you. Commissions don’t affect our rankings or reviews. How we make money

Michael has a diverse background in software engineering, mechanical engineering, economics, and management. After a successful career in mechanical engineering, Michael decided to become a software engineer and attended the Hack Reactor coding bootcamp. Michael enjoys writing about his experiences and helping others start their journeys in software development.