TExcelTAD
Home › 2D Games with JavaScript & Canvas › Pong 1: Paddles & Ball

Pong 1: Paddles & Ball

Pong is the "hello world" of game programming: two paddles, one ball and a score. It looks tiny, but it already needs everything a bigger game needs: input, movement, collision, scoring and game states. Over the next four lessons we build it step by step, and every step is a complete game you can play right here.

In this first step we put the pieces on the table: two paddles that move, and a ball that flies around and bounces off the top and bottom walls.

The plan

Lesson What we add
Pong 1 (this one) paddles, ball, wall bounces
Pong 2 paddle collisions, bounce angle, speed-up
Pong 3 score, serving, a computer opponent
Pong 4 title screen, pause, game over, restart

Every playground starts with the same play kit you met in The Game Canvas: a 480 × 270 canvas that scales to fit the frame, a keys set of held keys, a pressed set of keys pressed since the last update, the "Click to play" overlay, and run(update, draw), a fixed-step loop that calls update(dt) 60 times per second and draw() once per frame. The game code comes after the end of play kit comment.

Describing the game as data

Before any drawing, decide what the game is in numbers. Everything in Pong is a rectangle with a position and a size, and the ball also has a velocity:

js
const PADDLE_W = 8, PADDLE_H = 50, PADDLE_SPEED = 260;   // pixels, pixels per second
const left  = { x: 16, y: H / 2 - PADDLE_H / 2 };
const right = { x: W - 16 - PADDLE_W, y: H / 2 - PADDLE_H / 2 };
const ball  = { x: W / 2 - 4, y: H / 2 - 4, size: 8, vx: 180, vy: 120 };

Speeds are in pixels per second, not pixels per frame. Each update multiplies them by dt (the step length in seconds, 1/60 here), so the game runs at the same speed no matter how often the screen refreshes.

Step 1: moving paddles and a bouncing ball

Click the game, then hold W/S for the left paddle and ↑/↓ for the right one:

html · try it yourself
<style>
  html, body { margin: 0; height: 100%; background: #0e1018; overflow: hidden; }
  canvas { display: block; margin: 0 auto; width: min(100vw, 177.78vh); height: auto; outline: none; touch-action: none; }
</style>
<canvas width="480" height="270"></canvas>
<script>
// ---- play kit: click to focus, keep game keys inside the frame, fixed-step loop ----
const cv = document.querySelector('canvas'), ctx = cv.getContext('2d');
const W = cv.width, H = cv.height;
const keys = new Set(), pressed = new Set();   // keys held now / pressed since the last update
let active = false, idleDrawn = false;
cv.tabIndex = 0;
cv.addEventListener('pointerdown', () => cv.focus());
cv.addEventListener('focus', () => { active = true; });
cv.addEventListener('blur', () => { active = false; idleDrawn = false; keys.clear(); pressed.clear(); });
addEventListener('keydown', (e) => {
  if (e.code.startsWith('Arrow') || e.code === 'Space') e.preventDefault(); // don't scroll the lesson
  if (!e.repeat) pressed.add(e.code);
  keys.add(e.code);
});
addEventListener('keyup', (e) => keys.delete(e.code));
function banner(title, sub = '') {
  ctx.save();
  ctx.fillStyle = 'rgba(0,0,0,0.6)'; ctx.fillRect(0, 0, W, H);
  ctx.fillStyle = '#fff'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
  ctx.font = 'bold 22px system-ui, sans-serif'; ctx.fillText(title, W / 2, H / 2 - 10);
  ctx.font = '14px system-ui, sans-serif'; ctx.fillText(sub, W / 2, H / 2 + 18);
  ctx.restore();
}
function run(update, draw, help = '') {
  const STEP = 1 / 60;
  let acc = 0, last = performance.now();
  requestAnimationFrame(function frame(now) {
    const dt = Math.min((now - last) / 1000, 0.1);
    last = now;
    if (active) {
      acc += dt;
      while (acc >= STEP) { update(STEP); pressed.clear(); acc -= STEP; }
      draw();
    } else if (!idleDrawn) {
      draw(); banner('Click to play', help); idleDrawn = true;
    }
    requestAnimationFrame(frame);
  });
}
// ---- end of play kit ----

// ---- Pong, step 1: paddles and a bouncing ball ----
const PADDLE_W = 8, PADDLE_H = 50, PADDLE_SPEED = 260;
const left = { x: 16, y: H / 2 - PADDLE_H / 2 };
const right = { x: W - 16 - PADDLE_W, y: H / 2 - PADDLE_H / 2 };
const ball = { x: W / 2 - 4, y: H / 2 - 4, size: 8, vx: 180, vy: 120 };

function movePaddle(p, up, down, dt) {
  if (keys.has(up)) p.y -= PADDLE_SPEED * dt;
  if (keys.has(down)) p.y += PADDLE_SPEED * dt;
  p.y = Math.max(0, Math.min(H - PADDLE_H, p.y));   // stay on screen
}

function update(dt) {
  movePaddle(left, 'KeyW', 'KeyS', dt);
  movePaddle(right, 'ArrowUp', 'ArrowDown', dt);

  ball.x += ball.vx * dt;
  ball.y += ball.vy * dt;

  // Top and bottom walls: put the ball back inside and point vy away from the wall.
  if (ball.y < 0) { ball.y = 0; ball.vy = Math.abs(ball.vy); }
  if (ball.y + ball.size > H) { ball.y = H - ball.size; ball.vy = -Math.abs(ball.vy); }

  // Left or right edge: no paddles collide yet, so just re-centre the ball.
  if (ball.x + ball.size < 0 || ball.x > W) {
    ball.x = W / 2 - ball.size / 2;
    ball.y = H / 2 - ball.size / 2;
    ball.vx = -ball.vx;
  }
}

function draw() {
  ctx.fillStyle = '#0e1018';
  ctx.fillRect(0, 0, W, H);
  ctx.fillStyle = '#2a2f45';                        // dashed centre line
  for (let y = 4; y < H; y += 16) ctx.fillRect(W / 2 - 1, y, 2, 8);
  ctx.fillStyle = '#e8eaf6';
  ctx.fillRect(Math.round(left.x), Math.round(left.y), PADDLE_W, PADDLE_H);
  ctx.fillRect(Math.round(right.x), Math.round(right.y), PADDLE_W, PADDLE_H);
  ctx.fillStyle = '#ffb74d';
  ctx.fillRect(Math.round(ball.x), Math.round(ball.y), ball.size, ball.size);
}

run(update, draw, 'W/S and ↑/↓ move the paddles');
</script>

The ball passes straight through the paddles for now; that's the next lesson.

How the wall bounce works

A bounce is two operations: move the ball back inside the playfield and point the velocity away from the wall.

js
if (ball.y < 0) { ball.y = 0; ball.vy = Math.abs(ball.vy); }

Why Math.abs instead of ball.vy = -ball.vy? If the ball is still slightly inside the wall on the next step (for example after a big dt), flipping the sign again would send it back into the wall, and it would jitter along the edge. Forcing the sign ("down after hitting the top") can never get stuck. Moving the ball back to y = 0 is just as important for the same reason.

You can try the logic without a canvas. This is the same wall rule as a pure function, run for a few steps:

js · try it yourself
const H = 270, SIZE = 8, DT = 1 / 60;

function stepBall(ball) {
  let { y, vy } = ball;
  y += vy * DT;
  if (y < 0) { y = 0; vy = Math.abs(vy); }
  if (y + SIZE > H) { y = H - SIZE; vy = -Math.abs(vy); }
  return { y, vy };
}

let b = { y: 6, vy: -240 };          // close to the top, moving up fast
for (let i = 1; i <= 4; i++) {
  b = stepBall(b);
  console.log(`step ${i}: y=${b.y.toFixed(1)} vy=${b.vy}`);
}
step 1: y=2.0 vy=-240
step 2: y=0.0 vy=240
step 3: y=4.0 vy=240
step 4: y=8.0 vy=240

Clamping the paddles

Math.max(0, Math.min(H - PADDLE_H, p.y)) is a clamp: it keeps p.y between 0 and H - PADDLE_H. You will write clamps in every game you make, so many programmers keep a helper:

js
const clamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v));

Tip: Draw at Math.round(x). Positions are floating-point numbers like 118.33, and drawing at a fractional position makes the browser blend the edge across two pixels, so crisp rectangles turn blurry.

Note: Both players share one keyboard. Some keyboards can't report many keys at once ("ghosting"), so if W+S+↑+↓ held together drop a key, that's the hardware, not your code.

Test yourself

Why are speeds stored in pixels per second and multiplied by dt?

  1. It makes the numbers smaller
  2. So the game runs at the same speed whatever the update rate
  3. Canvas requires it
  4. To make collisions exact

After the ball goes past the top wall, why set vy = Math.abs(vy) instead of vy = -vy?

  1. Math.abs is faster
  2. Flipping twice could send the ball back into the wall; forcing the direction can't get stuck
  3. -vy is not valid JavaScript
  4. To make the ball speed up

What does Math.max(0, Math.min(H - PADDLE_H, y)) do?

  1. Rounds y
  2. Keeps y between 0 and H - PADDLE_H
  3. Finds the larger paddle
  4. Converts y to pixels