0 Spicy Yoghurt | Last updated: 26 November 2026 | HTML5 game tutorial
Build a 2D game camera in JavaScript
Every side-scroller needs a camera that follows the player. Learn how to build one in JavaScript on an HTML5 canvas, with a live demo for every step. You'll go from a camera that sticks to the player to dead zones, parallax backgrounds and screen shake.
Here's what you'll build: a small level that's four times as wide as the canvas, with a camera that follows the player through it. The player runs and jumps by itself. Click or tap the canvas to take over, then use the arrow keys or the buttons on the screen. Turn on Camera guides to see what the camera is doing:
The two red lines are the left and right edges of the dead zone, and the blue cross is the point the camera follows. By the end of this tutorial, you'll know what the dead zone and the blue cross do, and how to build every part of this camera yourself.
What is a camera in a 2D game?
In a lot of games, the level is much bigger than the screen. Think of a platformer like Super Mario Bros.: the level goes on and on to the right, but you only ever see a small part of it. Which part you see is up to the camera.
In a 2D game, the camera is a rectangle somewhere in the level, as big as the canvas: 750 by 400 pixels in this tutorial. Everything inside that rectangle ends up on the canvas. In code, it's an object with a position and a size:
const camera = {x: 0, y: 0, width: 750, height: 400};camera.x and camera.y give the position of the rectangle's top-left corner in the level. The player also has x, y, width and height, so player.x and player.y give the position of the player's top-left corner.
In the demo below, the map in the top-right corner shows the whole level, with the camera as a blue rectangle. Drag across the canvas to move the camera through the level, or drag the rectangle on the map. The code under the demo shows where the player and the camera are:
// Where the player is in the world
player.x = 1180;
// Where the camera is in the world
camera.x = 812;
// Where the player is on the canvas
let canvasX = player.x - camera.x; // 368Every object in the game has a position in the level, its world position. Moving the camera doesn't change the world position of anything. What changes is where an object shows up on the canvas: its world position minus the position of the camera. That's its canvas position. Part of the player is off the canvas when canvasX is below 0, or above 750 minus the width of the player.
Make the camera follow the player
So how do you draw everything at its canvas position? You could subtract camera.x and camera.y in every draw function, but there's a shorter way. context.translate() moves everything you draw after it, so you can move the whole level at once:
function draw() {
context.clearRect(0, 0, canvas.width, canvas.height);
// Put the camera's top-left corner at (0, 0) on the canvas
context.save();
context.translate(-camera.x, -camera.y);
drawPlatforms();
drawCoins();
drawPlayer();
context.restore();
// The score stays in place on the canvas
drawScore();
}drawPlatforms(), drawCoins(), drawPlayer() and drawScore() stand in for your own drawing code. The first three keep using world positions, and they don't need to know about the camera at all. With the camera at (812, 400), a platform at world position (812, 640) ends up at (0, 240) on the canvas. save() stores the current state of the canvas, and restore() brings it back, so translate() only affects what you draw in between. That's why drawScore(), which comes after restore(), draws at canvas positions again. The tutorial about animating size and rotation uses the same trick.
Canvas positions are what you want for the score, the lives and the buttons: everything that stays in place while the level moves. Together, they're called the HUD, short for heads-up display.
To make the camera follow the player, move it every frame so that the player ends up in the middle of the canvas:
function updateCamera() {
// Put the middle of the player in the middle of the camera
camera.x = player.x + player.width / 2 - camera.width / 2;
camera.y = player.y + player.height / 2 - camera.height / 2;
}Call updateCamera() in the game loop, after the player has moved and before you draw:
function gameLoop(timeStamp) {
let secondsPassed = (timeStamp - oldTimeStamp) / 1000;
oldTimeStamp = timeStamp;
updatePlayer(secondsPassed);
updateCamera();
draw();
window.requestAnimationFrame(gameLoop);
}The order matters. If you update the camera before the player, the camera uses the player's position from the previous frame. Frames don't all take the same amount of time, so the gap between the player and the middle of the canvas changes a little every frame, and the player seems to jitter.
The game loop and secondsPassed come from the tutorial about the JavaScript game loop. updatePlayer() moves the player with the arrow keys, as in the tutorial about game controls for keyboard, mouse and touch.
In the demo below, switch the camera off, and the player runs right off the canvas. With the camera on, the level moves instead, and the score stays in its corner:
A camera that's glued to the player has two problems, though. At the start and the end of the level, it shows what's beyond the edge. And it moves with every step and every jump, so the whole level never sits still. The next sections fix both.
Keep the camera inside the level
When the player stands at the left edge of the level, a camera that centers the player shows half a canvas of nothing. Most games stop the camera at the edges of the level instead. The camera stays put, and the player walks on toward the edge of the canvas.
The left edge of the camera can go from 0 up to the width of the level minus the width of the camera. Keep it between those two numbers with a small clamp() function:
function clamp(value, min, max) {
return Math.max(min, Math.min(value, max));
}Math.min() makes sure the value isn't higher than max, and Math.max() makes sure it isn't lower than min. Add two lines at the end of updateCamera():
// Keep the camera inside the level
camera.x = clamp(camera.x, 0, level.width - camera.width);
camera.y = clamp(camera.y, 0, level.height - camera.height);level holds the size of the level: 3,000 by 800 pixels in the demos on this page. Switch Level edges to Ignore to see the camera without these two lines. The dark area is outside the level:
What if the level is narrower than the canvas? Then the highest value for camera.x is below 0. Math.max() runs last in clamp(), so camera.x always ends up at 0, and the camera sticks to the left edge of the level. To put the level in the middle of the canvas instead, add this after the two lines with clamp():
if (level.width < camera.width) {
camera.x = (level.width - camera.width) / 2;
}For a level that's 500 pixels wide, camera.x becomes -125, so there's 125 pixels of empty space on both sides of the level.
Give the player room with a dead zone
A camera that keeps the player in the exact middle moves with every little step. When the player walks back and forth to line up a jump, the whole level slides back and forth with it. That's tiring to look at.
To fix this, add a dead zone: a rectangle in the middle of the camera, where the player can move without moving the camera. The camera only moves when the player walks out of the dead zone. When that happens, the camera moves just far enough to bring the player back to the edge of the dead zone. In Scroll Back, an overview of cameras in side-scrollers, Itay Keren calls a dead zone a camera window. Here's updateCamera() with a dead zone:
const deadZone = {width: 160, height: 120};
function updateCamera() {
let centerX = player.x + player.width / 2;
let centerY = player.y + player.height / 2;
// The edges of the dead zone, in the world
let left = camera.x + (camera.width - deadZone.width) / 2;
let right = left + deadZone.width;
let top = camera.y + (camera.height - deadZone.height) / 2;
let bottom = top + deadZone.height;
// Only move as far as the player is outside the dead zone
if (centerX < left) {
camera.x -= left - centerX;
} else if (centerX > right) {
camera.x += centerX - right;
}
if (centerY < top) {
camera.y -= top - centerY;
} else if (centerY > bottom) {
camera.y += centerY - bottom;
}
// Keep the camera inside the level
camera.x = clamp(camera.x, 0, level.width - camera.width);
camera.y = clamp(camera.y, 0, level.height - camera.height);
}The dead zone sits in the middle, so the room on either side of it is (camera.width - deadZone.width) / 2. If the middle of the player is 20 pixels to the right of the dead zone, the camera moves 20 pixels to the right, and the player is back at the edge of the dead zone. Try a small and a large dead zone in the demo below. The red rectangle is the dead zone:
A bigger dead zone makes the camera steadier. But then the player can get close to the edge of the canvas, and there's less to see in front of the player. Around a quarter of the canvas width is a good starting point: 160 to 200 pixels on a 750-pixel-wide canvas.
Make the camera move smoothly at any frame rate
With a dead zone, the camera starts and stops abruptly. As soon as the player pushes against the edge of the dead zone, the level moves at full speed. When the player stops, the level stops dead. It feels a lot smoother when the camera speeds up and slows down instead.
To do that, split the work in two. updateCamera() no longer moves the camera itself. Instead, it moves a target: the spot the camera heads for. Change camera.x and camera.y to target.x and target.y in the code for the dead zone and the edges of the level.
Then move the camera part of the way to the target every frame. You might have seen this common shortcut:
// Move 10% of the way to the target every frame
camera.x += (target.x - camera.x) * 0.1;
camera.y += (target.y - camera.y) * 0.1;This is called lerp smoothing. It's named after lerp(), short for linear interpolation. You may know lerp() from the tutorial about smooth canvas animations: it gives you a value that's a fraction of the way from one number to another. Every frame, the camera covers 10% of the distance that's left.
This shortcut looks great on your own screen, but it depends on the frame rate. On a 144 Hz screen, the game runs at 144 frames per second, so the camera takes more steps per second than on a 60 Hz screen. After every frame, 90% of the distance is left. Half a second at 60 fps is 30 frames, and 0.9 to the power of 30 is about 0.04, so 4% of the distance is left. At 144 fps, it's 0.05%, and at 30 fps, 21%.
So on a fast screen, the camera follows almost rigidly, and on a slow device, it lags far behind.
To fix this, take the time between frames into account:
// The spot the camera moves to, starting at the camera's position
const target = {x: camera.x, y: camera.y};
const cameraSpeed = 6;
function moveCamera(secondsPassed) {
let blend = 1 - Math.exp(-cameraSpeed * secondsPassed);
camera.x += (target.x - camera.x) * blend;
camera.y += (target.y - camera.y) * blend;
}Math.exp(-cameraSpeed * secondsPassed) is the fraction of the distance that's still left after secondsPassed seconds. blend is the fraction the camera covers in this frame. At 60 fps, blend is 0.095, almost the 0.1 from before. At 144 fps, it's smaller, and at 30 fps, it's bigger. The smaller blend at 144 fps makes up for the extra frames exactly, and the bigger one at 30 fps does the same for the missing ones. Two short frames leave the same fraction of the distance as one long frame that lasts as long as both together. That's because Math.exp(-a) * Math.exp(-b) is the same as Math.exp(-(a + b)). So after half a second, there's always Math.exp(-6 * 0.5) left, about 0.05: 5% of the distance. It's the same math that's behind the motion trails in the tutorial about smooth canvas animations. A higher cameraSpeed makes the camera follow more tightly.
Call moveCamera(secondsPassed) at the end of updateCamera(), and pass secondsPassed from the game loop to updateCamera().
The demo below can pretend to run at a different frame rate. The blue ring is the camera's target, and the gray circle is the middle of the camera. The top-left corner shows how far apart they are. Choose Frame-based, the 10% shortcut: at 30 fps, the camera falls farther behind than at 60 fps, and at 144 fps, it stays closer. With Time-based, the code with moveCamera(), the distance stays about the same at every frame rate:
The player runs at a steady speed, so the camera ends up a steady distance behind its target. At that distance, the camera moves exactly as far each frame as the player does. That's fine, as long as there's enough to see ahead of the player. The next section makes sure there is.
Let the camera look ahead of the player
When the player runs, the dead zone and the smoothing both let it get ahead of the middle of the camera. That leaves more of the level in view behind the player than in front of it. But what's behind is old news. What matters is what's coming: the next gap, the next enemy. So shift the camera forward, in the direction the player is facing. This is called look-ahead.
Put lookAhead, lookSpeed and lookOffset at the top of your script. In updateCamera(), replace the line that sets centerX with the last four lines of the code below:
// At the top of your script
const lookAhead = 120;
const lookSpeed = 2;
let lookOffset = 0;
// In updateCamera(), instead of the old centerX
let goal = player.facing * lookAhead;
let blend = 1 - Math.exp(-lookSpeed * secondsPassed);
lookOffset += (goal - lookOffset) * blend;
let centerX = player.x + player.width / 2 + lookOffset;player.facing is 1 when the player faces right, and -1 when it faces left. updatePlayer() sets it whenever the player runs left or right, as in the example code at the end of this page. The camera now follows a point 120 pixels in front of the player, instead of the player itself. When the player turns around, that point shouldn't jump to the other side, or every turn would make the camera lurch sideways. Instead, lookOffset glides to the other side, with the same smoothing as the camera. It's slower, though: lookSpeed is 2, and cameraSpeed is 6. Itay Keren calls this dual forward focus.
Turn look-ahead on and off in the demo below. The blue cross is the point the camera follows:
In a fast game, you can make the distance depend on the speed of the player: the faster the player runs, the farther the camera looks ahead.
Keep the camera steady when the player jumps
In a platformer, the player jumps all the time. A jump is higher than the dead zone, so the camera still bobs the whole level up and down with every jump. Many platformers handle up and down differently: the camera only moves up or down when the player lands. Itay Keren calls this platform snapping.
Replace the part of updateCamera() that moves the target up and down with this:
let feetY = player.y + player.height;
if (player.onGround) {
// Line the camera up with the platform under the player
target.y = feetY - camera.height * 0.7;
} else if (feetY > target.y + camera.height - 60) {
// Falling out of view: follow the fall
target.y = feetY - camera.height + 60;
} else if (player.y < target.y + 60) {
// Jumping out of view: follow the jump
target.y = player.y - 60;
}player.onGround is true when the player stands on the ground or a platform. The example code at the end of this page sets it when the player lands. When it's true, the camera puts the player's feet 70% of the way down the canvas, with more room above the player than below. While the player is in the air, the target stays where it is. The camera only follows when the player gets within 60 pixels of the top or the bottom of the canvas.
The camera itself still trails behind its target, though. On a long fall, the player drops faster than the camera follows, and disappears below the canvas for a moment. So after moveCamera(), clamp the camera position too:
// In updateCamera(), after moveCamera()
// A fast fall can outrun the smoothing, so keep the player
// at least 60 pixels inside the view
let minY = feetY - camera.height + 60;
let maxY = player.y - 60;
camera.y = clamp(camera.y, minY, maxY);
// And the camera inside the level
camera.y = clamp(camera.y, 0, level.height - camera.height);Now the player never goes out of view. The last line keeps the camera inside the level, just as the earlier code does for the target.
Compare Follow on landing and Always follow in the demo below. With Always follow, the camera also uses the dead zone when the player moves up and down:
Add depth with parallax scrolling
So far, the code clears the canvas and then draws the level, with nothing behind it. The demos on this page have mountains and hills in the background. That background makes the level look a lot more alive, especially because it doesn't scroll as fast as the level. Things far away seem to move more slowly than things close by. Think of the view from a train: the trees next to the track race by, while the mountains on the horizon hardly move. Recreating that in a game is called parallax scrolling, and it gives a flat game a sense of depth.
Draw the background in layers, each with its own speed:
const layers = [
{speed: 0.2, width: 600, draw: drawMountains},
{speed: 0.5, width: 500, draw: drawHills}
];
function drawBackground() {
for (let layer of layers) {
// How far this layer has scrolled, minus whole widths
let offset = (camera.x * layer.speed) % layer.width;
if (offset < 0) {
offset += layer.width;
}
let x = -offset;
while (x < canvas.width) {
layer.draw(x);
x += layer.width;
}
}
}A layer with a speed of 0.5 moves half as far as the camera, and one with 0.2 only a fifth. The level itself has a speed of 1, and a sky that doesn't move has a speed of 0.
Each layer is a picture that repeats, like wallpaper. width is the width of one copy, and drawMountains(x) draws one copy of the mountains with its left edge at x. The remainder operator % takes off whole widths, so the first copy starts at the left edge of the canvas or a bit before it. When camera.x is negative, as with a level that's narrower than the canvas, % gives a negative offset, and the if adds one width. The while loop adds copies until the canvas is full. With an image instead of shapes, layer.draw(x) would call drawImage(), as in the tutorial about images and sprite animations.
Call drawBackground() in draw() before save() and translate(), because the layers do their own scrolling. The layers only move sideways, so they stay put when the camera moves up and down. Make sure the left and right edges of a picture match, or you'll see a seam where two copies meet.
Switch parallax off and on in the demo below. Without parallax, the hills and mountains move along with the level, as if they were painted on a wall right behind it:
Zoom in and out
Zooming in makes everything bigger, so the camera sees a smaller part of the level. At a zoom of 2, it sees half as much in each direction: 375 by 200 pixels of the level fill the whole canvas. So the size of the camera depends on the zoom:
let zoom = 2;
camera.width = canvas.width / zoom;
camera.height = canvas.height / zoom;Everything in updateCamera() already uses camera.width and camera.height, so following the player and keeping the camera inside the level still work. In draw(), call scale() before translate():
context.save();
context.scale(zoom, zoom);
context.translate(-camera.x, -camera.y);Read these lines from the bottom up: the transformation you add last is the first to act on every point you draw. translate() moves the camera's corner to (0, 0), and then scale() makes everything twice as big around that corner. The camera is 375 pixels wide, and those 375 pixels become 750 on the canvas.
The dead zone is in world pixels, so at a zoom of 2, it covers twice as much of the canvas. To keep it the same size on the screen, use deadZone.width / zoom and deadZone.height / zoom in updateCamera().
To zoom smoothly, don't change zoom all at once. Put the zoom you want in targetZoom, and move zoom toward it in updateCamera(), the same way moveCamera() moves the camera:
const zoomSpeed = 5;
let targetZoom = 2;
// At the start of updateCamera()
let zoomBlend = 1 - Math.exp(-zoomSpeed * secondsPassed);
zoom += (targetZoom - zoom) * zoomBlend;
// Zoom around the middle of the camera, not its corner
let width = canvas.width / zoom;
let height = canvas.height / zoom;
let dx = (camera.width - width) / 2;
let dy = (camera.height - height) / 2;
camera.x += dx;
camera.y += dy;
target.x += dx;
target.y += dy;
camera.width = width;
camera.height = height;The camera and the target both store their top-left corner. When the camera changes size, both corners move by half the difference in width and height, so the middle of the camera stays where it is. Without that, the camera would zoom in and out from its top-left corner.
For a zoom that takes a fixed time, use an easing function instead. The animation tool for easing functions has an example of a camera that zooms in like that. Choose a zoom in the demo below to see the smooth zoom from the code above:
Turn a click into a position in the world
With a camera, a spot on the canvas isn't the same as a spot in the world anymore. Say the camera is at x = 1200 with no zoom, and you click 300 pixels from the left edge of the canvas. The spot you clicked is at x = 1500 in the world, not at 300. You need the world position whenever a click has to hit something in the level, like an enemy, a door or a tile to build on. In the demo further down, a click plants a flag, and flags is the array that holds them:
canvas.addEventListener('pointerdown', function (event) {
// Where the click is on the canvas
let rect = canvas.getBoundingClientRect();
let screenX = event.clientX - rect.left;
let screenY = event.clientY - rect.top;
let canvasX = screenX * canvas.width / rect.width;
let canvasY = screenY * canvas.height / rect.height;
// Where that is in the world
let worldX = canvasX / zoom + camera.x;
let worldY = canvasY / zoom + camera.y;
flags.push({x: worldX, y: worldY});
});The five lines under the first comment are the same as in the tutorial about game controls. They turn the position of the mouse or finger in the browser window into a position on the canvas, even when the canvas is shown smaller, like on a phone. Then the code undoes what draw() did: it divides by the zoom and adds the position of the camera. To go the other way, from the world to the canvas, use (worldX - camera.x) * zoom.
In the demo below, the camera has a zoom of 1.5. Click or tap the level to plant a flag. With Click position set to Canvas, the code uses the canvas position as if it were a world position, and the flag lands somewhere else in the level. The code under the demo shows the numbers for your last click:
// Click or tap the level to see the numbers
let worldX = canvasX / zoom + camera.x;
let worldY = canvasY / zoom + camera.y;To find out what a click hits, compare worldX and worldY with the world positions of the objects in the level. The tutorial about collision detection shows how to check whether a point is inside a shape.
Shake the screen
When something big happens, like an explosion or a hard landing, a short shake of the screen makes it hit harder. It's one of the cheapest ways to make a game feel alive, and it's all done with the camera.
A good shake starts strong and fades out. Squirrel Eiserloh explains a popular way to do this in his talk Juicing Your Cameras With Math. Keep a number called trauma, between 0 and 1. Every hit adds some trauma, and the trauma goes down a little every frame:
let trauma = 0;
const maxShake = 20;
function addTrauma(amount) {
trauma = Math.min(trauma + amount, 1);
}
// At the end of updateCamera()
trauma = Math.max(trauma - secondsPassed, 0);A full trauma of 1 takes one second to fade out. Call addTrauma(0.3) for a small bump, and addTrauma(1) for a big explosion. In draw(), turn the trauma into a random offset, and add that offset in translate():
// The shake grows with the square of the trauma
let shake = trauma * trauma;
let shakeX = maxShake * shake * (Math.random() * 2 - 1);
let shakeY = maxShake * shake * (Math.random() * 2 - 1);
context.save();
context.translate(-camera.x + shakeX, -camera.y + shakeY);Math.random() * 2 - 1 is a random number between -1 and 1, so the level moves at most 20 pixels left or right and at most 20 pixels up or down. The tutorial about random numbers in JavaScript explains how that works.
Because trauma is squared, a trauma of 0.5 gives only a quarter of the full shake. That way, small hits stay small, big hits really stand out, and the shake fades out gently at the end.
You can also tilt the level a little with every shake. Put these lines right after save() in draw(), before scale() and translate():
// Up to 0.05 radians, about 3 degrees
const maxAngle = 0.05;
let angle = maxAngle * shake * (Math.random() * 2 - 1);
context.translate(canvas.width / 2, canvas.height / 2);
context.rotate(angle);
context.translate(-canvas.width / 2, -canvas.height / 2);The first translate() moves (0, 0) to the middle of the canvas, rotate() turns everything around that point, and the second translate() moves (0, 0) back to the corner.
Press Small bump in the demo below a few times in a row to see the trauma add up, and Big explosion for the full shake. With Shake rotation on, the level tilts too:
Some people feel dizzy or even sick from a shaking screen. Add a setting to turn the shake off, and have it off by default when the device is set to reduce motion. The tutorial about smooth canvas animations shows how to check that setting.
More camera tricks from classic games
With a target and smoothing, you can build a lot of different cameras. Here are three tricks you'll find in many classic games, each a few lines on top of the camera you have now:
- Room by room - The camera shows one room at a time. When the player walks out of a room, the camera slides over to the next one, like in the original Legend of Zelda.
- Two players - The camera follows the point halfway between two players, and zooms out when they move apart, so they both stay in view.
- Cutscene - When the player touches a lever, the camera moves to the door that the lever opens, waits a moment and moves back.
Pick one in the demo below:
For rooms, divide the level into rooms as big as the canvas. Then aim the camera at the room the player is in, instead of at the player. This replaces the dead zone, the look-ahead and the platform snapping in updateCamera():
// The middle of the player
let centerX = player.x + player.width / 2;
let centerY = player.y + player.height / 2;
// The room the player is in
let roomX = Math.floor(centerX / camera.width);
let roomY = Math.floor(centerY / camera.height);
target.x = roomX * camera.width;
target.y = roomY * camera.height;Math.floor() rounds down, so roomX is 0 for any centerX below 750, and 1 from 750 up to just below 1500. The smoothing from before makes the camera slide from room to room. A higher cameraSpeed makes the slide quicker.
For two players, measure the distance between them, and pick the zoom that fits it:
let center1 = player1.x + player1.width / 2;
let center2 = player2.x + player2.width / 2;
// The distance between them, plus 150 pixels on each side
let distance = Math.abs(center1 - center2) + 300;
targetZoom = clamp(canvas.width / distance, 0.5, 1);
target.x = (center1 + center2) / 2 - camera.width / 2;For target.y, use the point halfway between the two players in the same way. The zoom stays between 0.5 and 1, so the players never get too small, and the camera never zooms in closer than normal. At a zoom of 0.5, the camera is 1,500 pixels wide, so the players can be up to 1,200 pixels apart. Many games stop the players from moving farther apart than that.
For a cutscene, give the camera something else to follow for a while. Keep the object the camera follows in a variable, and use it in updateCamera() instead of player:
let focus = player;
let leverPulled = false;
function openDoor() {
// Only once, even if the player stays on the lever
if (leverPulled) {
return;
}
leverPulled = true;
focus = door;
door.isOpening = true;
// Back to the player after 2.5 seconds
setTimeout(function () {
focus = player;
}, 2500);
}door is an object with x, y, width and height, like the player, so updateCamera() can follow it. door.isOpening tells your own door code to slide the door up. leverPulled makes sure the cutscene plays only once. Without it, openDoor() would run again on every frame the player touches the lever. The player is still standing on the lever when the camera comes back, so the cutscene would start all over again. Use the look-ahead and the platform snapping only while focus is the player, because a door doesn't face a direction or stand on a platform. While focus is the door, set target.y so that the door is in the middle of the camera. Call openDoor() when the player touches the lever. The camera glides to the door, and back to the player 2.5 seconds later. In most games, the player can't move during a cutscene, so make updatePlayer() ignore the keys until focus is the player again.
Common questions about game cameras
Why does the screen look jittery when the camera moves?
Usually, it's because the camera position isn't a whole number. Then the edges of your images and shapes fall between two pixels, and they shimmer while the camera moves. Round the camera position when you draw: context.translate(-Math.round(camera.x), -Math.round(camera.y)). With a zoom, round camera.x * zoom and camera.y * zoom instead, then divide the results by the zoom. The tutorial about smooth canvas animations has more about fixing shaky edges with whole pixels. Also check the order in the game loop: first the player, then the camera, then draw().
Should I move the camera or move the world?
On the screen, both look the same. But move the world with translate(), not by changing the position of every object. Then every object keeps its own position in the world. That's what you want: your game logic, collisions and enemies work with world positions, and only draw() and the code that handles clicks need to know about the camera.
How do I draw only what the camera sees?
Skip every object that's completely outside the camera. The object and the camera are both rectangles, so you can use the check for two overlapping rectangles from the tutorial about collision detection. With a few hundred objects, the canvas is fast enough to draw them all, so only do this when you notice your game slowing down.
How do I make a camera for a top-down game?
The same way, but up and down work just like left and right. Use the dead zone on both axes, and skip the platform snapping, because nobody jumps. Look-ahead works on both axes too, toward where the player is moving.
How do I rotate the camera?
Rotate around the middle of the canvas, as with the shake rotation in this tutorial, and then move the level with the camera as before. Keep in mind that a click then needs one more step to become a world position: before you divide by the zoom, rotate the click around the middle of the canvas by the same angle in the opposite direction.
How do I add a minimap?
Draw the level a second time, much smaller, in a corner of the canvas, after restore(). Use scale() with a small number, such as 0.1, and draw the camera on top as a rectangle, like the map in the first section of this page.
How do cameras work in Phaser or PixiJS?
Phaser has a camera in every scene, this.cameras.main. Its methods match the parts of this tutorial:
- startFollow(player) - Follows the player.
- setBounds() - Keeps the camera inside the level.
- setDeadzone() - Adds a dead zone.
- setLerp() - Smooths the movement.
- shake() and zoomTo() - Add screen shake and zoom.
PixiJS has no built-in camera: you put the whole level in a container and move that container, just like translate() does here.
Example code: a side-scrolling camera
Here's an example page that puts the main parts of the camera from this tutorial together in a single HTML file. There's a level with platforms, and a player that runs with the arrow keys and jumps with the up arrow or Space. The camera in the example uses these parts:
- Dead zone - Sideways only.
- Smoothing - With moveCamera(), the same at any frame rate.
- Look-ahead - 120 pixels in front of the player.
- Platform snapping - Up and down only when the player lands, or gets close to the top or bottom of the view.
- Level edges - The camera stays inside the level.
- Parallax - Two layers, mountains and hills.
- Screen shake - After a hard landing, unless the device is set to reduce motion.
Paste the code below into an HTML file and open it in your browser:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>2D Game Camera Tutorial | Spicy Yoghurt</title>
</head>
<body>
<h1>2D game camera tutorial by Spicy Yoghurt</h1>
<canvas
id="canvas"
width="750"
height="400"
tabindex="0"
style="border:1px solid lightgray;"
>
Your browser does not support the HTML5 canvas tag.
</canvas>
<p>
Click the canvas. Run with the left and right arrow keys,
and jump with the up arrow or Space.
</p>
<script>
'use strict';
let canvas;
let context;
let oldTimeStamp = 0;
// The level is four times as wide as the canvas
const level = {width: 3000, height: 800};
// The ground and the platforms; you land on top of them
const platforms = [
{x: 0, y: 740, width: 3000, height: 60},
{x: 350, y: 640, width: 180, height: 20},
{x: 600, y: 540, width: 160, height: 20},
{x: 850, y: 440, width: 200, height: 20},
{x: 1120, y: 340, width: 220, height: 20},
{x: 1420, y: 440, width: 160, height: 20},
{x: 1700, y: 600, width: 220, height: 20},
{x: 2000, y: 500, width: 160, height: 20},
{x: 2250, y: 400, width: 180, height: 20},
{x: 2520, y: 300, width: 200, height: 20},
{x: 2800, y: 620, width: 150, height: 20}
];
// A coin above every platform
const coins = platforms.slice(1).map(function (platform) {
return {
x: platform.x + platform.width / 2,
y: platform.y - 50,
taken: false
};
});
let score = 0;
const player = {
x: 100,
y: 700,
width: 36,
height: 40,
vx: 0,
vy: 0,
facing: 1,
onGround: false
};
const runSpeed = 260;
const jumpSpeed = 820;
const gravity = 2000;
// The camera is a rectangle in the level, as big as the canvas
const camera = {x: 0, y: 400, width: 750, height: 400};
// The spot the camera moves to
const target = {x: 0, y: 400};
// Sideways only; for up and down, the camera waits for a landing
const deadZone = {width: 160};
const cameraSpeed = 6;
const lookAhead = 120;
const lookSpeed = 2;
let lookOffset = 0;
// Screen shake, but not when the device is set to reduce motion
let trauma = 0;
const maxShake = 20;
const reduceMotion =
window.matchMedia('(prefers-reduced-motion: reduce)').matches;
// The background layers, and how fast they scroll
const layers = [
{speed: 0.2, width: 600, draw: drawMountains},
{speed: 0.5, width: 500, draw: drawHills}
];
// The keys that are down right now
const keys = {};
const gameKeys = ['ArrowLeft', 'ArrowRight', 'ArrowUp', 'Space'];
window.onload = init;
function init() {
canvas = document.getElementById('canvas');
context = canvas.getContext('2d');
canvas.addEventListener('keydown', function (event) {
keys[event.code] = true;
// Keep the arrow keys and Space from scrolling the page
if (gameKeys.includes(event.code)) {
event.preventDefault();
}
});
canvas.addEventListener('keyup', function (event) {
keys[event.code] = false;
});
// Release all keys when the canvas loses focus
canvas.addEventListener('blur', function () {
for (let code in keys) {
keys[code] = false;
}
});
canvas.focus();
window.requestAnimationFrame(gameLoop);
}
function gameLoop(timeStamp) {
let secondsPassed = (timeStamp - oldTimeStamp) / 1000;
oldTimeStamp = timeStamp;
// After a pause, don't jump ahead too far
secondsPassed = Math.min(secondsPassed, 0.1);
updatePlayer(secondsPassed);
updateCamera(secondsPassed);
draw();
window.requestAnimationFrame(gameLoop);
}
function updatePlayer(secondsPassed) {
// Run left or right
let direction = 0;
if (keys.ArrowLeft) {
direction -= 1;
}
if (keys.ArrowRight) {
direction += 1;
}
if (direction != 0) {
player.facing = direction;
}
player.vx = direction * runSpeed;
// Jump, but only from the ground or a platform
if ((keys.ArrowUp || keys.Space) && player.onGround) {
player.vy = -jumpSpeed;
}
player.vy += gravity * secondsPassed;
let oldBottom = player.y + player.height;
player.x += player.vx * secondsPassed;
player.y += player.vy * secondsPassed;
player.x = clamp(player.x, 0, level.width - player.width);
landOnPlatforms(oldBottom);
collectCoins();
}
function landOnPlatforms(oldBottom) {
let bottom = player.y + player.height;
player.onGround = false;
for (let platform of platforms) {
let isOver =
player.x + player.width > platform.x &&
player.x < platform.x + platform.width;
// Falling, and the feet went through the top this frame
if (
isOver && player.vy >= 0 &&
oldBottom <= platform.y && bottom >= platform.y
) {
// A hard landing, faster than 1100 pixels per second,
// shakes the screen
if (player.vy > 1100) {
addTrauma(0.5);
}
player.y = platform.y - player.height;
player.vy = 0;
player.onGround = true;
}
}
}
function collectCoins() {
let centerX = player.x + player.width / 2;
let centerY = player.y + player.height / 2;
for (let coin of coins) {
let dx = Math.abs(coin.x - centerX);
let dy = Math.abs(coin.y - centerY);
// The coin is close enough to the player's middle
// to touch the player
if (!coin.taken && dx < 30 && dy < 35) {
coin.taken = true;
score++;
}
}
}
function updateCamera(secondsPassed) {
// Look ahead in the direction the player is facing
let goal = player.facing * lookAhead;
let blend = 1 - Math.exp(-lookSpeed * secondsPassed);
lookOffset += (goal - lookOffset) * blend;
let centerX = player.x + player.width / 2 + lookOffset;
// Move the target only when centerX leaves the dead zone
let left = target.x + (camera.width - deadZone.width) / 2;
let right = left + deadZone.width;
if (centerX < left) {
target.x -= left - centerX;
} else if (centerX > right) {
target.x += centerX - right;
}
// Up and down only when the player lands, or gets close to
// the top or bottom of the view
let feetY = player.y + player.height;
if (player.onGround) {
target.y = feetY - camera.height * 0.7;
} else if (feetY > target.y + camera.height - 60) {
target.y = feetY - camera.height + 60;
} else if (player.y < target.y + 60) {
target.y = player.y - 60;
}
// Keep the target inside the level
target.x = clamp(target.x, 0, level.width - camera.width);
target.y = clamp(target.y, 0, level.height - camera.height);
moveCamera(secondsPassed);
// A fast fall can outrun the smoothing, so keep the player
// at least 60 pixels inside the view
let minY = feetY - camera.height + 60;
let maxY = player.y - 60;
camera.y = clamp(camera.y, minY, maxY);
// And the camera inside the level
camera.y = clamp(camera.y, 0, level.height - camera.height);
// Let the shake fade out
trauma = Math.max(trauma - secondsPassed, 0);
}
// Move the camera part of the way to the target
function moveCamera(secondsPassed) {
let blend = 1 - Math.exp(-cameraSpeed * secondsPassed);
camera.x += (target.x - camera.x) * blend;
camera.y += (target.y - camera.y) * blend;
}
function clamp(value, min, max) {
return Math.max(min, Math.min(value, max));
}
function addTrauma(amount) {
if (reduceMotion) {
return;
}
trauma = Math.min(trauma + amount, 1);
}
function draw() {
context.clearRect(0, 0, canvas.width, canvas.height);
drawBackground();
// The shake grows with the square of the trauma
let shake = trauma * trauma;
let shakeX = maxShake * shake * (Math.random() * 2 - 1);
let shakeY = maxShake * shake * (Math.random() * 2 - 1);
// Put the camera's top-left corner at (0, 0) on the canvas
context.save();
context.translate(
-Math.round(camera.x) + shakeX,
-Math.round(camera.y) + shakeY
);
drawPlatforms();
drawCoins();
drawPlayer();
context.restore();
// The score stays in place on the canvas
drawScore();
}
function drawBackground() {
context.fillStyle = '#e0f3f6';
context.fillRect(0, 0, canvas.width, canvas.height);
for (let layer of layers) {
// How far this layer has scrolled, minus whole widths
let offset = (camera.x * layer.speed) % layer.width;
if (offset < 0) {
offset += layer.width;
}
let x = -offset;
while (x < canvas.width) {
layer.draw(x);
x += layer.width;
}
}
}
function drawMountains(x) {
context.fillStyle = '#c4d3ea';
context.beginPath();
context.moveTo(x, 300);
context.lineTo(x + 150, 140);
context.lineTo(x + 300, 300);
context.lineTo(x + 420, 190);
context.lineTo(x + 600, 300);
context.lineTo(x + 600, 400);
context.lineTo(x, 400);
context.fill();
}
function drawHills(x) {
context.fillStyle = '#9be4b8';
context.beginPath();
context.moveTo(x, 330);
context.quadraticCurveTo(x + 125, 230, x + 250, 330);
context.quadraticCurveTo(x + 375, 260, x + 500, 330);
context.lineTo(x + 500, 400);
context.lineTo(x, 400);
context.fill();
}
function drawPlatforms() {
for (let platform of platforms) {
context.fillStyle = '#c09480';
context.fillRect(
platform.x, platform.y,
platform.width, platform.height
);
// Grass on top
context.fillStyle = '#37c871';
context.fillRect(
platform.x, platform.y, platform.width, 8
);
}
}
function drawCoins() {
context.fillStyle = '#ffcf51';
context.strokeStyle = '#ffb900';
context.lineWidth = 3;
for (let coin of coins) {
if (!coin.taken) {
context.beginPath();
context.arc(coin.x, coin.y, 10, 0, Math.PI * 2);
context.fill();
context.stroke();
}
}
}
function drawPlayer() {
context.fillStyle = '#ff8080';
context.beginPath();
context.roundRect(
player.x, player.y, player.width, player.height, 14
);
context.fill();
// Two eyes that look the way the player is facing
let eyeX = player.x + player.width / 2 + player.facing * 6;
let eyeY = player.y + 14;
for (let x of [eyeX - 7, eyeX + 7]) {
context.fillStyle = 'white';
context.beginPath();
context.arc(x, eyeY, 6, 0, Math.PI * 2);
context.fill();
context.fillStyle = '#303030';
context.beginPath();
let pupilX = x + player.facing * 2;
context.arc(pupilX, eyeY, 3, 0, Math.PI * 2);
context.fill();
}
}
function drawScore() {
context.fillStyle = '#303030';
context.font = '22px Arial';
context.fillText('Coins: ' + score, 16, 32);
}
</script>
</body>
</html>Conclusion
A camera in a 2D game is a rectangle in the level. Move the level with translate(), and whatever is inside that rectangle ends up on the canvas. Everything else is about where the rectangle goes. It follows the player, stays inside the level and holds still while the player is in the dead zone. It glides to its target the same way at any frame rate, looks ahead and waits for a landing. On top of that come parallax, zoom and screen shake.
Which of these you need depends on your game. A puzzle game might only need to keep the camera inside the level, and a fast platformer might need all of them. Start from the example code, add what your game needs, and tweak the numbers until the camera feels right.
That's all for now. If you have any questions, feel free to ask them in the comment section. You can download the example code here.
Comments
Thanks! We've received your comment. We check every comment by hand before it appears, so this can take a few days.

No comments yet. Be the first to leave one!