Clear, practical technology insights BSOD Code Lookup · Windows Error Code Lookup · Wi-Fi Troubleshooting · PC Troubleshooting Checklist

Build a One-Button Side-Scrolling Game in JavaScript

Create an original canvas game with gravity reversal, moving barriers, collision checks and scoring in a single HTML file.

Table of Contents

You can build a one-button side-scroller in JavaScript with one HTML file and no downloaded assets. In Signal Run, each press reverses gravity. A square slides along the top or bottom of the play area until you steer it around a barrier. Passing a barrier scores one point.

Save and run the game

Save this example as index.html, then open it in a browser. Start with Space, a tap on the canvas or the button. Use the same control to reverse direction. If you hit a barrier, start again with the button.

<!doctype html>
<html lang="en">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Signal Run</title>
<h1>Signal Run</h1>
<p>Press Space, tap the play area or use the button to reverse gravity.</p>
<canvas id="game" width="360" height="260" style="display:block;max-width:100%;touch-action:manipulation"></canvas>
<button id="control" type="button">Start</button>
<script>
const canvas = document.querySelector('#game');
const ctx = canvas.getContext('2d');
const control = document.querySelector('#control');
const width = canvas.width;
const height = canvas.height;
const pilotX = 70;
const size = 18;
let pilotY, velocity, gravity, barriers, score, cooldown;
let status = 'ready';
let lastTime;

function reset() {
  pilotY = (height - size) / 2;
  velocity = 0;
  gravity = 210;
  barriers = [];
  score = 0;
  cooldown = 0.8;
}

function action() {
  if (status !== 'playing') {
    reset();
    status = 'playing';
    control.textContent = 'Reverse gravity';
    return;
  }
  gravity *= -1;
  velocity = 0;
}

control.addEventListener('click', action);
canvas.addEventListener('pointerdown', action);
window.addEventListener('keydown', event => {
  if (event.code === 'Space' && event.target !== control) {
    event.preventDefault();
    if (!event.repeat) action();
  }
});

function update(dt) {
  velocity += gravity * dt;
  pilotY += velocity * dt;
  if (pilotY < 0 || pilotY > height - size) {
    pilotY = Math.max(0, Math.min(height - size, pilotY));
    velocity = 0;
  }

  cooldown -= dt;
  if (cooldown <= 0) {
    const top = Math.random() < 0.5;
    barriers.push({ x: width, y: top ? 0 : height - 100, counted: false });
    cooldown = 2.2;
  }

  for (const barrier of barriers) {
    barrier.x -= 115 * dt;
    const overlapsX = pilotX < barrier.x + 22 && pilotX + size > barrier.x;
    const overlapsY = pilotY < barrier.y + 100 && pilotY + size > barrier.y;
    if (overlapsX && overlapsY) {
      status = 'over';
      control.textContent = 'Play again';
      return;
    }
    if (!barrier.counted && barrier.x + 22 < pilotX) {
      barrier.counted = true;
      score += 1;
    }
  }
  barriers = barriers.filter(barrier => barrier.x + 22 > 0);
}

function draw() {
  ctx.fillStyle = '#172038';
  ctx.fillRect(0, 0, width, height);
  ctx.fillStyle = '#f89849';
  for (const barrier of barriers) ctx.fillRect(barrier.x, barrier.y, 22, 100);
  ctx.fillStyle = '#61dfdb';
  ctx.fillRect(pilotX, pilotY, size, size);
  ctx.fillStyle = '#fff';
  ctx.font = '16px system-ui';
  const instruction = status === 'over' ? ' / Game over' : '';
  ctx.fillText('Score: ' + score + instruction, 12, 24);
}

function frame(time) {
  const dt = Math.min(0.04, (time - (lastTime ?? time)) / 1000);
  lastTime = time;
  if (status === 'playing') update(dt);
  draw();
  requestAnimationFrame(frame);
}
reset();
requestAnimationFrame(frame);
</script>
</html>

How movement, collisions and scoring work

requestAnimationFrame supplies a timestamp. The game converts the elapsed time into seconds so motion has roughly the same speed on different displays. Each barrier moves left and leaves a route on one side. A collision occurs only when the pilot and barrier overlap both horizontally and vertically. After a barrier’s right edge passes the pilot, a flag keeps it from awarding a second point.

What to try next

Increase the time between barriers to make the game easier, or lower the barrier height to give players more room. Test the keyboard, canvas and button separately. Check that holding Space does not repeatedly flip gravity and that restarting clears the score. Use the HTML canvas reference to explore other shapes or the JavaScript learning path to practice events and arrays.

Discussion

Reader Comments 0

Sign in with email or Google to join the discussion.