Make your first game in 30 lines of JavaScript
You don't need special software to make a game. A text editor and a web browser are enough. In this guide you'll build Catch the Star: a basket at the bottom of the screen and a star falling from the top. Catch it to score a point.
Step 1: make the file
Open any text editor (Notepad works, but VS Code is nicer) and save an empty file called game.html. Paste in the code below, save, and double-click the file to open it in your browser.
<canvas id="c" width="400" height="500" style="background:#12152b"></canvas>
<script>
const ctx = document.getElementById("c").getContext("2d");
let basketX = 170, starX = 200, starY = 0, score = 0;
// 1. Input: move the basket with the arrow keys
addEventListener("keydown", (e) => {
if (e.key === "ArrowLeft") basketX -= 25;
if (e.key === "ArrowRight") basketX += 25;
});
function loop() {
// 2. Update: the star falls
starY += 4 + score * 0.3;
if (starY > 460 && starX > basketX && starX < basketX + 60) {
score++; starY = 0; starX = Math.random() * 380 + 10; // caught it!
}
if (starY > 500) { score = 0; starY = 0; } // missed: start again
// 3. Draw: clear, then paint everything
ctx.clearRect(0, 0, 400, 500);
ctx.fillStyle = "#ffc94d"; ctx.font = "28px sans-serif"; ctx.fillText("★", starX - 10, starY);
ctx.fillStyle = "#2ee6c9"; ctx.fillRect(basketX, 470, 60, 14);
ctx.fillStyle = "#fff"; ctx.font = "18px sans-serif"; ctx.fillText("Score: " + score, 10, 24);
requestAnimationFrame(loop); // do it all again next frame
}
loop();
</script>
Step 2: understand what you wrote
- The canvas is the game screen: 400 pixels wide and 500 tall.
- The variables remember where the basket and star are, and the score.
- The keydown listener moves the basket when you press the arrow keys.
- The loop moves the star down, checks whether it landed in the basket, and draws everything.
requestAnimationFrameruns the loop again about 60 times a second.
Notice the three steps from How a browser game works: input, update, draw.
Step 3: make it yours
Here are some ideas to try. Change one thing at a time, save, and refresh the browser to see what happens:
- Change the colours (
#ffc94dis yellow,#ff4d8dis pink). - Make the basket wider, or the star fall faster.
- Keep a best score that doesn't reset when you miss.
- Add a second star, or a "bad" star you must avoid.
- Add a sound when you catch a star (search for "Web Audio API beep").
Where to go next
Every game on Noam's Game Hub started with the same idea, just with more objects and more rules. Play a few games and think about what each one is doing in its loop. What does Snake update each frame? How does Brick Smash know which brick the ball hit? Thinking like that is the first step to making your own.