How to Make Pong in JavaScript: Step by Step

how to make pong in javascript

To learn how to make Pong in JavaScript, build it around a ball that moves by velocity each frame, then add wall bounces, paddles, collision, scoring and a simple computer opponent in that order.

Picture a blank canvas and a ball that either flies off the edge or sticks to a paddle. Pong is a good place to learn why. It is a two-player table tennis-themed video game, and its motion is continuous rather than stepped. Each stage below adds one behaviour, so you can test it before moving on. If you want the wider picture first, read how to make a browser game. The guide assumes you know basic JavaScript and have an HTML page with a canvas element.

Quick answer: draw with the Canvas API, run an animation loop, add velocity to the ball’s position every frame, reverse the matching velocity component on a bounce, test overlap between ball and paddle with a rectangle check, award a point when the ball passes a paddle, then reset the ball. Finish with a computer paddle that follows the ball.

Prerequisites and the finished result

You need one HTML file, one canvas element and one script. The result is a playable Pong game with a paddle on each side, a bouncing ball, a score for each player and either a second human or a computer opponent.

Keep the game state small. You need a ball with a position and a velocity, two paddles with a position, size and vertical velocity, and two score counters. Everything else is drawing and rules built on those values.

This approach differs from grid games. If you have built how to make snake game in javascript, you moved a snake one cell at a time. Pong has no cells. The ball can be at any position on the canvas, and its speed and direction are stored as numbers you update continuously.

Canvas and game loop

Start by selecting the canvas element and getting its rendering context. One tutorial begins exactly this way, selecting the canvas and then calling getContext(‘2d’). Every rectangle, line and circle you draw goes through that context.

  1. Get the canvas and its context once, outside the loop.
  2. Write a draw function that clears the canvas and paints the background, the centre line, both paddles and the ball.
  3. Write an update function that changes positions but draws nothing.
  4. Call both from a single loop function that schedules itself with requestAnimationFrame.

Use requestAnimationFrame for the loop. Jake Gordon’s JavaScript Pong write-up builds on a 60 fps double-buffered canvas game loop. It also warns that a low-fidelity timer such as setInterval is not going to work for serious games.

Checkpoint: the canvas should show a static scene with both paddles and the ball, and the loop should keep running without errors in the browser console. Do not add movement until this works.

Moving the ball with velocity

The ball is the heart of the game, and its motion is simple. Give it a position (x and y) and a velocity (dx and dy). In every update, the position advances by the velocity: the straker gist adds dx to x and dy to y on each loop.

Treat dx as horizontal speed and dy as vertical speed. A positive dx sends the ball right, a negative dx sends it left, and the same applies to dy up and down. Serve with a non-zero value on both axes so the first shot is diagonal and the ball does not travel along a single line.

Avoid setting the position directly anywhere except at a reset. Changing velocity and letting the update apply it keeps all movement in one place, which makes bugs much easier to trace.

Bouncing off the walls

The ball bounces by changing the sign of the velocity component for the axis it hit. At the top and bottom walls, reverse dy. At a paddle, reverse dx. The FoolishDev tutorial describes the same idea: once a collision is detected, the ball’s direction is reversed.

Do the wall test after moving the ball. If the ball’s top edge is above the top of the canvas, or its bottom edge is below the bottom, flip dy. Then put the ball back just inside the boundary so it cannot stay stuck outside and flip again on the next frame.

Leave the left and right edges alone for now. Those are scoring zones, not bounce zones.

Checkpoint: with no paddles active, the ball should travel diagonally, bounce off the top and bottom indefinitely and leave through the sides. If it jitters at a wall, the ball is being left outside the boundary after the flip.

Paddles and keyboard controls

Each paddle needs a position, a size and a vertical velocity. In the straker gist the paddle height is 80 px, and the paddle speed is 6 units per frame. Those are reasonable starting values to tune by feel.

Keyboard events drive the paddles. Use a keydown listener to set the paddle’s vertical velocity, and a keyup listener to set it back to zero so the paddle stops when the key is released. In the GeeksforGeeks tutorial, player one uses the W key to move up, with S for down, which gives two people room on one keyboard.

A paddle and ball on a court with painted boundary lines.

In the update step, add the paddle velocity to its y position, then clamp it. The gist clamps paddles so they do not go through the walls: the position cannot go above the top wall or below the maximum Y that keeps the paddle’s bottom on the canvas.

Checkpoint: each paddle should move only while its key is held, stop when released and never leave the canvas. If a paddle keeps drifting after you release a key, the keyup handler is not clearing its velocity.

Detecting the ball hitting a paddle

Use an axis-aligned bounding box (AABB) test. The gist checks collision between two objects using AABB, and the test compares each object’s edges with the other’s. Two rectangles overlap only when their x ranges and their y ranges both intersect. Written out, all four of these must be true:

  • Left of the ball before right of the paddle: obj1.x < obj2.x + obj2.width.
  • Right of the ball after left of the paddle: obj1.x + obj1.width > obj2.x.
  • Top of the ball above bottom of the paddle: obj1.y < obj2.y + obj2.height.
  • Bottom of the ball below top of the paddle: obj1.y + obj1.height > obj2.y.

Here obj1 is the ball and obj2 is a paddle. The simplest approach is to treat the ball as a small square for this test, which keeps the maths to those four comparisons. A true rectangle-circle test is more precise, but a square ball rarely looks wrong at game speed.

When the test passes, reverse dx. The Lance multiplayer tutorial does the same: when the ball moving left hits the player one paddle, its x velocity is multiplied by -1.

Then move the ball next to the paddle. The gist moves the ball beside the paddle after a hit because otherwise the collision will happen again on the next frame. Set the ball’s x to the paddle’s edge, on the side it came from.

A paddle and ball positioned close together on a table.

Checkpoint: the ball should rebound once per hit and never pass through a paddle that is in its way. If it vibrates inside the paddle, the repositioning step is missing.

Scoring and resetting the ball

A point is scored when the ball gets past a paddle and reaches a side wall. The GeeksforGeeks tutorial says that if the ball hits the wall, it is a score for the other player. The gist leaves this as an exercise: when a ball goes past a paddle, the other player should score a point.

Handle it in this order, so a score is only counted once:

  1. Check whether the ball has crossed the left or right edge.
  2. Add one to the score of the opposite player.
  3. Reset the ball to the middle of the canvas, as the FoolishDev tutorial does when the ball goes out of bounds.
  4. Serve it again toward a player with a fresh velocity.

Add a short pause before the serve. The gist uses a delay to give the player time to recover before launching the ball again. A simple way is a flag that stops the ball moving until a timer ends.

Draw the scores each frame near the top of each half. Because the draw function runs every frame, the displayed score always matches the stored value.

A simple computer opponent

A computer opponent is a paddle whose velocity is set by code instead of the keyboard. Jake Gordon’s Pong adds a rudimentary AI for the computer player, which shows that a very simple rule is enough for a first version.

The easiest rule is to compare the centre of the paddle with the ball’s y position in each update. If the ball is above the centre, give the paddle an upward velocity. If it is below, give it a downward velocity. Otherwise set the velocity to zero. Reuse the same clamp that keeps human paddles on the canvas.

Do not let the computer move faster than a human can. A paddle that always matches the ball perfectly is impossible to beat and no fun to play. Give it a speed limit at or below the human paddle speed, and it will occasionally miss steeply angled shots, which makes rallies fair.

Only react while the ball is travelling toward the computer’s side if you want it to look more natural. When the ball is moving away, the paddle can simply stay put.

Final checks before you stop

The game is complete enough to stop when all of the following work together without console errors:

  • Serve and rally: the ball starts diagonally, bounces off the top and bottom, and returns from both paddles.
  • Controls: each paddle responds only to its keys and stays inside the canvas.
  • Score and reset: a missed ball adds a point for the other side and puts the ball back in the middle after a pause.
  • Opponent: the computer paddle tracks the ball and sometimes loses.

From here, a natural next project is how to make a platformer in javascript, which reuses the velocity and overlap ideas with gravity added.

Frequently asked questions

Why use requestAnimationFrame instead of setInterval for Pong?

Jake Gordon’s write-up argues that a low-fidelity timer like setInterval is not going to work for serious games, and builds its loop on requestAnimationFrame instead.

Can I control a paddle with the mouse instead of the keyboard?

Yes. One alternative tutorial listens for mouse movements to control the left paddle, using the mouse’s vertical position rather than key presses.

Does the ball curve between bounces?

No. In the Lance tutorial, the ball’s velocity can change suddenly when it hits a wall or a paddle, so you apply the change at the hit and otherwise leave the velocity alone.

Why does the ball get stuck on a paddle?

The ball is still overlapping the paddle on the next frame, so the collision fires again. Place the ball against the paddle’s edge when you reverse its horizontal velocity.