If you want to learn 2d game programming for beginners, start with plain JavaScript on an HTML canvas before choosing an engine: write a loop, move a sprite, add input, then test collisions. Pick an engine once tooling matters more than understanding.
The first decision is how much you want to build yourself. This guide walks through each building block in the order you would meet it, and points to deeper guides such as what is a game loop when you want the full treatment of one topic.
Where to start: the first decision
Your starting point depends on what you want to learn and how quickly you need something playable. Three paths suit most beginners, and none of them is wrong. They differ in how much of the machinery you see.
- Plain JavaScript and an HTML canvas. Choose this if you want to understand how a game works. You write the loop, the input handling and the collision checks yourself, so every rule is visible in a few lines of code. It suits anyone who already knows a little JavaScript and prefers small, readable programs to editor windows full of panels.
- A block-based tool such as MakeCode Arcade. Choose this if text code is the obstacle. GameFromScratch describes MakeCode as an incredibly easy to use Lego-like programming option that comes with tools and assets for 2D games. It gets a result on screen fast, but it hides the loop and collision logic you will eventually want to understand.
- A full engine such as Unity, Godot or Unreal. Choose this when you already know what you want to make and need physics, sprite tooling and level editors. The same GameFromScratch guide warns that the learning curve of these engines is simply too high for complete beginners and that it often takes a very long time to see results.
The rest of this article assumes the first path, because it teaches the ideas that every other path reuses. A loop, a state object, input and collision checks exist in every 2D game, whether you write them or an engine does. If you later move to an engine, you will recognise what its components are doing.
The parts every 2D game shares
A 2D game is a program that repeatedly changes a description of the game world and then draws it. A walkthrough of building a game on canvas puts the minimum plainly: just about any canvas game has some kind of state, a way to update that state through an update loop, and user input. That gives three basic parts, and drawing is the step that makes the state visible.
Thinking in these parts helps you diagnose problems. If a character does not move, the fault is in input or update. If it moves in memory but not on screen, the fault is in drawing. If it moves through a wall, the fault is in collision. Keeping the parts separate in your code means each bug has a small search area.
State
State is the data that describes the game right now: where the player is, how big it is, which direction it faces, the score. Start with a plain object such as a player with x, y, width, height and speed. Resist storing anything in drawing code that the next frame needs, because drawing should only read state, never own it.
Update and draw
Update changes state, and draw paints it. Writing them as two separate functions called from one loop is the habit that pays off most as the game grows. It also lets you change how often you update without touching how you draw.
Input
Input events should write into state or into a small input record, not move things directly. Update then reads that record on each frame. The input section below shows the pattern.

Game library or game engine
A library is code you call from your own program, while an engine is a framework that calls your code. The difference decides who owns the main loop and the structure of your project.
Unity shows the engine side clearly. Its manual explains that scripts you create inherit from the MonoBehaviour class, so your code lives inside the engine’s object model. The same manual describes scripts as responding to input from the player and arranging for events in the gameplay to happen when they should. The engine decides when your script runs, and your job is to fill in the behaviour.
The browser canvas sits at the other end. It gives you a drawing surface and a way to ask for the next animation frame, and nothing else. You decide what an object is, when to update it and how to check overlaps. That is more work and less tooling, but it is also why a canvas is a good place to learn.
- Choose a library or raw canvas when you want to see every rule in your own code and the project is small enough to hold in your head.
- Choose an engine when you need physics, a visual editor, sprite management or tilemap tooling more than you need to understand the internals.
- Move later, not first. Learning on a canvas first makes engine terms such as collider, sprite and tilemap feel familiar rather than magical.
Setting up an HTML canvas
A canvas game needs an HTML canvas element, a script, and a reference to the drawing context. The element is a blank rectangle on the page, and everything you see in the game is drawn onto it by script.
To draw, ask the element for its 2D context. In the canvas game walkthrough, the author uses the getContext method of the canvas element to get a reference to the 2d drawing context, and then paints with it. For a first game that mostly means fillRect, which paints a filled rectangle. The same example uses fillRect to paint the whole canvas black as a background and again to draw a box standing in for a sprite.
Rectangles are the right placeholder art. They force you to get movement, input and collision working before you spend time on images, and a rectangle has exactly the shape your first collision check will use. The browser’s developer tools are the other piece of setup worth doing now, because logging a value from the loop is the quickest way to see what your state really holds.

The game loop
The game loop is the code that runs over and over, updating the game and then drawing it. In a browser you build it with requestAnimationFrame rather than a timer. The canvas walkthrough states this directly: it uses requestAnimationFrame to create the loop rather than setTimeout.
A loop built this way asks the browser to call your function before the next repaint, and your function asks again at the end. The shape is small enough to read at a glance.
let last = performance.now();
function frame(now) {
const dt = now – last;
last = now;
update(dt);
draw();
requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
The value dt is the time elapsed since the last tick, and it matters for movement. In the canvas example, that elapsed time is used in the expressions that set the delta values of the x and y properties. Multiplying speed by elapsed time means a character covers the same distance whether frames arrive quickly or slowly. Without it, a game runs faster on a fast machine and slower on a slow one.
That approach is a variable timestep. It is the simplest to write and a reasonable place to start. Once you need physics that behaves identically every run, the trade-offs are worth reading in fixed timestep vs variable timestep game loop.
Sprites and drawing
A sprite is a 2D graphic object that represents something in the game. Unity’s manual says plainly that sprites are used for all types of 2D games, which fits the idea that the player, enemies, pickups and scenery are all just images with a position.
For a first game, a sprite can be a coloured rectangle from fillRect. When you replace it with artwork, keep the sprite’s drawing position separate from its collision rectangle. A character image often has transparent margins, and a collision box that matches the visible body feels fairer than one that matches the whole image.
Animation, when you add it, is a matter of choosing which part of an image to draw on each frame. Store the current frame number in state and advance it from update, using elapsed time so animation speed does not depend on frame rate. Draw should only read that frame number and paint the matching piece of the sheet.
- Placeholder rectangles first. Get movement and collision right while art is still cheap to change.
- One state object per sprite. Position, size and animation frame live together, so draw and collision code read the same data.
- Art last. Replacing a rectangle with an image should change only the draw step.
How 2D collision detection works
Collision detection checks whether the shapes of two objects overlap. Unity’s manual defines a collision in just those terms: it occurs when the physics engine detects that the colliders of two game objects make contact or overlap. A 2D collider is the component that defines the shape of an object for the purposes of physical collisions.
A collider is deliberately simpler than the artwork. A character with a complicated outline is represented by a rectangle or circle, because testing overlap between simple shapes is quick and easy to get right. That simplified box is a bounding box. When its sides stay parallel to the screen’s axes, it is called axis-aligned, and the check reduces to comparing ranges on each axis.
function overlaps(a, b) {
return a.x < b.x + b.w && a.x + a.w > b.x && a.y < b.y + b.h && a.y + a.h > b.y;
}
Two boxes overlap only when their ranges overlap on both axes. That is the whole idea, and the dedicated guide on axis aligned bounding box collision expands it with edge cases. A broader 2d collision detection tutorial places it among the other methods.
Choosing a shape for the check
- Axis-aligned boxes suit platformers, grids and most first games. They are quick to write and quick to run, but they do not follow rotated shapes closely.
- Circles suit round objects and pickups, and are covered in circle collision detection.
- Rotated convex shapes need a more general test. A game programming slide deck on collision detection notes that any pair of non-intersecting polytopes has a separating axis orthogonal to a face or edge pair, which is the basis of the separating axis theorem. Reach for it only when boxes and circles stop being good enough.
Many objects: broad phase first
Checking every object against every other becomes wasteful as the object count grows. The same slide deck splits collision detection into phases, and the broad phase is the one that determines all pairs of objects that potentially collide. Exact tests then run only on those candidate pairs. If your game has many moving things, read about broad phase collision detection, and then about quadtree collision detection as one way to do it.
Detecting a collision is only half the job. What the game does next, such as stopping the player, bouncing a ball or damaging an enemy, is a separate decision, covered under collision response 2d game.
Handling keyboard and other input
To handle keyboard input in a game, record which keys are down when events fire, and read that record inside your update step. Do not move the player directly inside an event handler. Events arrive when the browser decides, while your game should change state at a steady point in the loop.
const keys = {};
addEventListener(“keydown”, e => keys[e.code] = true);
addEventListener(“keyup”, e => keys[e.code] = false);
Inside update, check the record and move accordingly, for example by adding speed times elapsed time to x when the right arrow is held. This keeps input and movement decoupled, so holding two keys at once behaves sensibly and the same code works whatever the frame rate. Unity’s description of its scripts matches this division of labour: scripts respond to input from the player and arrange for events in the gameplay to happen when they should. A canvas game does the same job in your own update function.

Keyboard is the right first input because it needs no extra setup. The reasoning behind more advanced patterns is in keyboard input handling game, which goes further into held keys and key mapping.
Pointer and gamepad
Pointer input suits menus, puzzle games and anything you aim. The guide to mouse input in canvas game covers reading clicks and touches. Controllers use a separate browser interface, described in gamepad api javascript, and are worth adding once the keyboard version plays well.

Tile maps and level design
A tile map builds a level from a grid of reusable tiles instead of one large image. Each cell holds a number that says which tile belongs there, and the game draws the grid by looking up each number. Levels become data that you can edit, load and save without touching the drawing code.
Engines treat this as a standard feature. Unity’s manual points to its 2D Tilemap Editor package, which is installed by default, as the way to use tilemaps. In plain JavaScript, a tile map is an array plus a tile size, and finding the tile under a point is a short calculation.
const col = Math.floor(x / tileSize);
const row = Math.floor(y / tileSize);
const tile = map[row * columns + col];
That lookup also gives you collision for free. To test whether the player is standing in a wall, look up the tile under each corner of the player’s box and check whether it is solid. This is far cheaper than comparing the player against every wall as a separate object. The full walkthrough is in how to make a tilemap.
Tile maps are worth adding when you notice yourself placing many similar rectangles by hand. For a first game with a single screen, hand-placed objects are fine, and the tile map can wait for your second project.
Organising code as the game grows
Organisation matters when the update function starts to feel crowded. The first sign is usually that menus, gameplay and game-over screens are all tangled into one set of if statements. A clear way to separate them is to give the game a current state and let each state own its own update and draw logic, which is the subject of game state management.

The second sign is that every object type needs a slightly different set of behaviours, and class hierarchies become awkward. Many games solve this by building objects from small reusable components rather than inheritance, an approach introduced in entity component system explained. You do not need either pattern for a first game, and adding them too early makes a small program harder to read, not easier.
- Stay flat while the game fits on a single screen and a handful of objects.
- Split by screen when menus and gameplay start to interfere with each other.
- Split by component when objects share behaviours but not much else.
Building a simple 2D game with JavaScript
A simple game in JavaScript can be built in a short sequence of working steps, each of which leaves you with something that runs. Course outlines follow the same order. A CodeHS JavaScript course, for example, introduces the canvas and graphics before it reaches mouse events, key events and collisions.

- Create the canvas and get the context. Fill the background with fillRect so you can see that drawing works.
- Define the state. Make a player object with position, size and speed, and a list for anything else on screen.
- Start the loop. Call requestAnimationFrame, compute elapsed time, then call update and draw.
- Draw the player as a rectangle. Confirm that changing state changes the picture.
- Add keyboard input. Record key state and move the player in update using elapsed time.
- Add an obstacle or a pickup. Run the overlap check each frame and decide what a collision does.
- Add rules. A score, a goal and a way to restart turn a demo into a game.
- Replace rectangles with art. Do this last, once the game is already fun with rectangles.
Test after each step rather than at the end. When something breaks, you know it was the last thing you changed. The browser’s developer tools help here, because you can log state from the loop and watch it change.
A learning path at a glance
The table below puts the building blocks in the order they are usually added, with what each one does and when to reach for it.
| Building block | What it does | Plain JavaScript starting point | Planning use |
|---|---|---|---|
| State | Describes the game at this moment | A plain object holding position, size and speed | Define before you draw anything |
| Update loop | Changes state over time | A function called through requestAnimationFrame | The first thing to get running |
| User input | Feeds changes into state | Key and pointer event listeners | Add once drawing and movement work |
| Drawing | Paints the state on the canvas | fillRect on the 2D context | Use rectangles until the rules work |
| Sprite | A 2D graphic object for the thing on screen | A rectangle, later an image | Swap art in last |
| Collider | Defines an object’s shape for collisions | A box with x, y, width and height | Keep separate from the artwork |
| Tile map | Builds a level from a grid of tiles | An array of tile numbers and a tile size | Add when hand-placed objects get tedious |
The descriptions of state, the update loop, input and canvas painting follow the canvas game walkthrough, while the sprite, collider and tilemap entries follow the Unity 6.1 manual.
Frequently asked questions
Why do fast objects sometimes pass through walls?
Collision checks run at discrete moments, and object placements are computed for those moments only. A game programming reference explains that if collisions are checked only for the sampled moments, some collisions are missed. This is called tunneling, and it is most likely with small, fast objects and thin walls.
Do I need a sprite atlas for my first game?
No. A sprite atlas is an optimisation, and Unity describes it as consolidating textures into a single combined texture, which optimizes the game and saves memory. A first game built from rectangles and a few images gains little from it. Consider one when you manage many separate images.
How do I get a mouse click position on a canvas?
Read the click event’s coordinates relative to the canvas, not the page. The canvas example does this with the getBoundingClientRect method of the target element to get element-relative coordinates.



