Rows of stage lights casting beams through the haze

Raycasting in JavaScript: build a 3D maze on a 2D canvas

Raycasting turns a 2D grid into a 3D maze you can walk through. Build your own raycaster in JavaScript, step by step: cast rays across the grid, fix the fisheye effect, and add textured walls and sprites.

Here's what you'll build: a 3D maze, drawn on an ordinary 2D canvas. The player walks through it by itself, picks up the chili peppers and looks for the green door. Click or tap the canvas to take over, and use the arrow keys, WASD or the on-screen buttons:

There's no 3D library behind this, and no WebGL. For every frame, the code sends one ray into the maze for each column of pixels on the canvas, and draws one thin strip of wall per ray. By the end of this tutorial, you'll be able to build this raycaster yourself, from the maze to the textures and the chilies.

What is raycasting?

Raycasting is a way to draw a 3D view from a flat map. The level is a grid seen from above, like a sheet of graph paper where some squares are walls. The player stands somewhere on that grid and looks in a direction.

To draw what the player sees, you send a ray from the player into the grid for every column of pixels on the canvas. Each ray points a little farther to the left or right than the one next to it, so together they fan out over everything the player can see. A ray stops at the first wall it hits, and the distance it traveled determines how tall that column of wall is on the screen. Close walls are tall, and walls far away are short.

In the demo below, the map is on the left and the player's view is on the right. The player walks around by itself. Move your mouse over the view, or tap it, to see which ray belongs to which column. With Rays set to 8, the view is made of eight wide strips, one per ray. Switch to 32, and the strips get narrower. With All, they're so narrow that the walls look solid:

Rays

This is how Wolfenstein 3D drew its levels in 1992. It only works because the world follows a few strict rules. All walls stand on a grid, they're all the same height, and you can't look up or down. So each column of pixels shows at most one piece of wall, centered on the horizon, and one ray tells you all you need to draw that column.

One ray per column makes it fast: 750 rays for a canvas 750 pixels wide, instead of one for every pixel. That was fast enough for a PC in 1992, and it's more than fast enough for a canvas in your browser today.

Store the level in a grid

The level is an array of strings, one string per row of the grid. A dot is floor, a # is a wall, and a W is a wall of wooden planks. That's the same kind of level as in the tutorials about pathfinding and maze generation, so you can use the levels and mazes from those tutorials here too. Click or drag on the map in the demo below to add or remove walls, and watch the array change:

Live demo The code updates as you play around
let level = [
    '################',
    '#......#.......#',
    '#.WW...#..#....#',
    '#.W.......#.WW.#',
    '#.....##..#..W.#',
    '###.......###..#',
    '#.....#.....#..#',
    '#..#..#.WW.....#',
    '#..#...........#',
    '################'
];

Keep a wall all around the edge of the level. That way, the player can't walk off the grid, and every ray hits a wall before it can leave the array. In the demo, you can't remove the walls along the edge.

The player is an object with a position and an angle:

let player = {x: 2.5, y: 4.5, angle: 0};

x and y are measured in cells, not pixels, and they don't have to be whole numbers. This player stands in the middle of the cell in column 2 and row 4: counting starts at 0, and 2.5 is halfway between 2 and 3. angle is the direction the player is facing, in radians. With an angle of 0, the player looks to the right on the map. Because y goes down on a canvas, a bigger angle turns the player clockwise.

To find out what's at a position, round both numbers down with Math.floor(). That gives you the column and the row of the cell. Pick the row first, and then the character in that row:

function isWall(x, y) {
    return level[Math.floor(y)][Math.floor(x)] != '.';
}

Every character that isn't a dot counts as a wall. That way, you can add other kinds of walls, each with its own letter, like the W.

Move and turn the player

The player turns with the left and right arrow keys, and walks forward and back with the up and down arrow keys. Use an object to keep track of which keys are held down, as the tutorial about keyboard, mouse and touch controls shows. Here, that object is called keys, and keys.ArrowLeft is true while you hold down the left arrow key. The example code at the end of this page uses two event listeners to fill keys, and also accepts W, A, S and D.

Turning changes the angle. Walking moves the player in the direction of the angle: Math.cos() of the angle tells you how far to go along x, and Math.sin() how far along y. Multiply the turn speed and the walking speed by secondsPassed, the time since the last frame, so the player moves at the same speed at any frame rate. The tutorial about the JavaScript game loop explains how to measure that time:

const moveSpeed = 3;   // Cells per second
const turnSpeed = 2.5; // Radians per second

function update(secondsPassed) {
    if (keys.ArrowLeft) {
        player.angle -= turnSpeed * secondsPassed;
    }
    if (keys.ArrowRight) {
        player.angle += turnSpeed * secondsPassed;
    }
    let move = 0;
    if (keys.ArrowUp) {
        move += 1;
    }
    if (keys.ArrowDown) {
        move -= 1;
    }
    let distance = move * moveSpeed * secondsPassed;
    movePlayer(
        Math.cos(player.angle) * distance,
        Math.sin(player.angle) * distance
    );
}

movePlayer() only moves the player if there's no wall in the way. The simplest version checks the new position, and doesn't move the player at all if that position is inside a wall. That works, but it feels sticky: walk into a wall at an angle, and the player stops dead.

In most games, the player slides along the wall instead. To get that, try the two directions one at a time. First move along x if there's room, and then along y if there's room:

const playerRadius = 0.2;

function movePlayer(stepX, stepY) {
    // Try each direction on its own, so you slide along a wall
    let marginX = stepX > 0 ? playerRadius : -playerRadius;
    if (!isWall(player.x + stepX + marginX, player.y)) {
        player.x += stepX;
    }
    let marginY = stepY > 0 ? playerRadius : -playerRadius;
    if (!isWall(player.x, player.y + stepY + marginY)) {
        player.y += stepY;
    }
}

The margin keeps the player at least 0.2 cells away from every wall. Without it, the player could stand right against a wall, and that wall would fill the whole view.

In the demo below, the player walks around the map by itself. With Slide along walls off, it gets stuck every time it walks into a wall at an angle. Turn Slide along walls on, and the player glides along the walls. Click or tap the map to take over and walk around yourself:

Slide along walls

movePlayer() checks only one point in each direction the player moves. For a maze with straight walls, that's enough. For round objects or diagonal walls, the tutorial about collision detection shows how to check circles and rectangles.

Step along the ray until it hits a wall

Now for the rays. Each ray starts at the player and goes in a straight line, at its own angle, until it hits a wall. You need to know how far it went.

The first idea most people have is to walk along the ray in small steps. Start at the player, take a small step in the direction of the ray, and check if you're in a wall yet. If not, take another step:

function castRay(angle) {
    let stepSize = 0.02;
    let x = player.x;
    let y = player.y;
    let distance = 0;
    while (!isWall(x, y)) {
        x += Math.cos(angle) * stepSize;
        y += Math.sin(angle) * stepSize;
        distance += stepSize;
    }
    return distance;
}

That works, but you have to choose a step size, and there's no good choice. In the demo below, move your mouse over the map, or tap it, to aim the ray. With a step size of 0.5, the ray takes big steps and needs only a few of them. But it can step right over the corner of a wall, and then that wall turns red: it's the wall the ray should have hit. Even when the ray does hit a wall, it stops somewhere inside that wall, up to half a cell too far. With a step size of 0.02, the ray is accurate, but look at the number of steps in the top-left corner:

Step size

A ray 10 cells long takes 500 steps of 0.02. The view in this tutorial has 750 rays, one for each column of a canvas 750 pixels wide. That's hundreds of thousands of steps for every frame. So how do you get a ray that's both fast and accurate?

Step from grid line to grid line with DDA

A wall always fills a whole cell. So you don't need to check every point along the ray, only the points where it enters a new cell. The ray enters a new cell every time it crosses a grid line. That's either a vertical line, between two columns of cells, or a horizontal line, between two rows.

The trick is to always jump to whichever grid line the ray reaches first. This is called DDA, short for digital differential analyzer. It's also how the classic raycasting tutorial by Lode Vandevenne does it, in C++.

In the demo below, a dark blue dot marks every vertical grid line the ray crosses, and a green dot every horizontal one. The light blue cells are the cells the ray passes through, and the dark outline marks the wall it hits. Aim the ray with your mouse or your finger:

To find the next grid line, you need two numbers for x and two for y:

  • deltaDistX - How far the ray travels from one vertical grid line to the next. Because the ray is straight, that's the same every time.
  • sideDistX - How far the ray travels from the player to the next vertical grid line.
  • deltaDistY and sideDistY - The same, for the horizontal lines.

At every step, the smaller of sideDistX and sideDistY tells you which line the ray reaches first. The ray steps into the next cell in that direction, and the sideDist of that direction grows by its deltaDist:

function castRay(angle) {
    let dirX = Math.cos(angle);
    let dirY = Math.sin(angle);
    // The cell the ray starts in
    let cellX = Math.floor(player.x);
    let cellY = Math.floor(player.y);
    // How far the ray goes to cross one whole cell
    let deltaDistX = Math.abs(1 / dirX);
    let deltaDistY = Math.abs(1 / dirY);

    // Which way the ray steps, and how far to the first line
    let stepX = 1;
    let sideDistX = (cellX + 1 - player.x) * deltaDistX;
    if (dirX < 0) {
        stepX = -1;
        sideDistX = (player.x - cellX) * deltaDistX;
    }
    let stepY = 1;
    let sideDistY = (cellY + 1 - player.y) * deltaDistY;
    if (dirY < 0) {
        stepY = -1;
        sideDistY = (player.y - cellY) * deltaDistY;
    }

    // Jump to the nearest grid line until the ray is in a wall
    while (true) {
        let distance;
        let vertical;
        if (sideDistX < sideDistY) {
            distance = sideDistX;
            sideDistX += deltaDistX;
            cellX += stepX;
            vertical = true;
        } else {
            distance = sideDistY;
            sideDistY += deltaDistY;
            cellY += stepY;
            vertical = false;
        }
        if (level[cellY][cellX] != '.') {
            return {
                distance: distance,
                vertical: vertical,
                wall: level[cellY][cellX],
                x: player.x + dirX * distance,
                y: player.y + dirY * distance
            };
        }
    }
}

dirX and dirY are how far the ray goes along x and y when it travels a distance of one cell. If dirX is 0.5, the ray has to travel 2 cells to get one cell farther along x: that's deltaDistX, 1 divided by 0.5. Math.abs() makes deltaDistX positive, because a ray that goes to the left still travels a positive distance. For a ray that goes straight up or down, dirX is 0, and in JavaScript, 1 divided by 0 is Infinity. That's fine: then sideDistX is Infinity too, and never the smaller one.

stepX is 1 if the ray goes to the right, and -1 if it goes to the left. At the start, sideDistX is the distance to the first vertical line on that side. For a ray going right, that line is cellX + 1 - player.x away along x, and for a ray going left, player.x - cellX. Multiplying by deltaDistX turns that into a distance along the ray.

Besides the distance, castRay() returns whether the last grid line it crossed was vertical, which wall the ray hit, and where. You'll need those later, for the shading and the textures.

With DDA, a ray to a wall 10 cells away takes 10 to 15 steps instead of 500: one for every vertical and every horizontal grid line it crosses. And DDA can't miss a wall, because it checks every cell the ray passes through.

Turn distances into walls

Now you can draw the view. The player sees a slice of the world in front of it, called the field of view. In this tutorial, it's 60 degrees, or Math.PI / 3 in radians, a common choice for raycasters. Spread the rays evenly over those 60 degrees, one ray per column, from the left edge of the canvas to the right edge.

How tall should the wall be in each column? Think of the canvas as a screen between the player and the world, like a window. Every wall is 1 cell tall, as tall as a cell is wide. Say the screen is 650 pixels from the player's eye. Then a wall 1 cell away is 650 pixels tall on the canvas, and a wall 2 cells away is half that: 325 pixels. So the height on the canvas is the distance from the eye to the screen, in pixels, divided by the distance to the wall.

Where does 650 come from? Half the width of the canvas (375 pixels) covers half the field of view (30 degrees). With a bit of trigonometry, that puts the screen about 650 pixels away. That's 375 divided by the tangent of 30 degrees:

// How wide the player can see: 60 degrees
const fov = Math.PI / 3;
// How far the screen is from the player's eye, in pixels
let screenDistance = canvas.width / 2 / Math.tan(fov / 2);

function drawWalls() {
    for (let column = 0; column < canvas.width; column++) {
        let angle = player.angle - fov / 2 + fov * column / canvas.width;
        let hit = castRay(angle);
        let height = screenDistance / hit.distance;
        let top = (canvas.height - height) / 2;
        context.fillStyle = '#0099b0';
        context.fillRect(column, top, 1, height);
    }
}

canvas is the canvas element, and context is its 2D drawing context, as in the tutorial about setting up an HTML5 canvas. Work out screenDistance once, after you have the canvas.

Each wall is centered on the middle of the canvas, the horizon, so the same amount sticks out above and below it. Before the walls, draw a ceiling in the top half of the canvas and a floor in the bottom half. The floor gets lighter toward the bottom of the canvas, so it seems to come closer:

function draw() {
    // The ceiling, and a floor that gets lighter up close
    let half = canvas.height / 2;
    context.fillStyle = '#303030';
    context.fillRect(0, 0, canvas.width, half);
    let floor =
        context.createLinearGradient(0, half, 0, canvas.height);
    floor.addColorStop(0, '#303030');
    floor.addColorStop(1, '#808080');
    context.fillStyle = floor;
    context.fillRect(0, half, canvas.width, half);

    drawWalls();
}

Call update() and draw() in your game loop, like gameLoop() in the example code, and you have a 3D view. In the demo below, the player walks through the level by itself, and you can click or tap to take over:

It looks 3D, but something's off. Walk up to a wall and look straight at it: the wall bulges toward you, as if you're looking through a fisheye lens. That's the fisheye effect, and it's the most common problem with raycasters.

Fix the fisheye effect

When you look straight at a flat wall, the ray in the middle of the view goes straight ahead, and the rays at the edges go out at an angle. Those rays are longer, even though they hit the same flat wall. At the edge of a 60-degree field of view, the ray is 15% longer than the one in the middle. So the wall comes out about 13% shorter there, because 1 divided by 1.15 is 0.87. That's why the wall bulges.

For the height of the wall, you need to know how far away the wall is straight ahead, not the length of the ray. The ray is the longest side of a right triangle, and the distance straight ahead is the side along the direction the player is facing. That side is the length of the ray multiplied by the cosine of the angle between the ray and that direction. For the ray in the middle, that angle is 0 and the cosine is 1, so nothing changes. Toward the edges, the cosine gets smaller, and the distance shrinks just enough to make up for the longer ray.

In the demo below, the player stands in front of a long, straight wall and turns slowly from side to side. Turn Fisheye fix on and off to see the difference:

Fisheye fix

With the fix, the top and the bottom of the wall are straight lines, wherever the player looks.

There's one more, smaller problem. The rays are spread evenly over 60 degrees, but the screen is flat. On a flat screen, rays with equal angles between them land farther apart near the edges. But each ray still gets a column of the same width, so near the edges, a wider piece of the world gets squeezed into each column.

To fix this, pick the column and work out the angle, instead of picking the angle and seeing where the ray lands. A column is screenX pixels from the middle of the canvas, and the screen is screenDistance pixels away. Math.atan(screenX / screenDistance) gives you the angle between the ray and the direction the player is facing. Add player.angle to that, and you have the angle of the ray. Here's drawWalls() with both fixes:

function drawWalls() {
    for (let column = 0; column < canvas.width; column++) {
        // The ray through the middle of this column
        let screenX = column + 0.5 - canvas.width / 2;
        let angle =
            player.angle + Math.atan(screenX / screenDistance);
        let hit = castRay(angle);
        // The distance straight ahead, without the fisheye effect
        let distance =
            hit.distance * Math.cos(angle - player.angle);
        let height = screenDistance / distance;
        let top = (canvas.height - height) / 2;
        context.fillStyle = '#0099b0';
        context.fillRect(column, top, 1, height);
    }
}

The 0.5 puts the ray through the middle of the column instead of its left edge. With one ray through each column of the flat screen, nothing gets squeezed, and every straight wall has straight edges.

Shade the walls by direction and distance

With one color for every wall, it's hard to see where one wall ends and the next one begins. Two kinds of shading help a lot.

First, make the walls that run one way a bit darker than the walls that run the other way. castRay() already tells you which kind of grid line the ray crossed last. On a vertical grid line, the ray hits a wall that faces left or right on the map, and on a horizontal grid line, a wall that faces up or down. Draw a dark, semi-transparent strip over the walls on vertical grid lines, and every corner stands out.

Second, let walls far away fade into the dark, as if there's fog. Draw a strip in the color of the ceiling over each wall, and make it more opaque the farther away the wall is. At 8 cells, the strip is fully opaque, and the wall disappears. Both strips go right after the line that draws the wall in drawWalls():

const fogDistance = 8;

function drawWalls() {
    for (let column = 0; column < canvas.width; column++) {
        // ...
        context.fillRect(column, top, 1, height);

        // Walls on a vertical grid line are a bit darker
        if (hit.vertical) {
            context.fillStyle = 'rgba(0, 0, 0, 0.3)';
            context.fillRect(column, top, 1, height);
        }
        // The farther away, the more the wall fades into the dark
        let fog = Math.min(distance / fogDistance, 1);
        context.fillStyle = 'rgba(48, 48, 48, ' + fog + ')';
        context.fillRect(column, top, 1, height);
    }
}

The color 48, 48, 48 is #303030, the color of the ceiling. The floor fades into the same color at the horizon, so walls in the distance blend in with both. Turn the two kinds of shading on and off in the demo below:

Shade by wall direction
Fog

Add textures to the walls

A texture is a small image that you stretch over a wall. Each column of the canvas shows one thin vertical slice of the texture. Which slice depends on where the ray hit the wall.

castRay() returns the point where the ray hit the wall, in hit.x and hit.y. On a vertical grid line, hit.x is a whole number, so you need hit.y. On a horizontal line, it's the other way around. Take the part after the decimal point, and you know where along the wall the ray hit: 0 at one end, 1 at the other. Multiply that number by the width of the texture, and you have the column of the texture to draw:

// Where the ray hit the wall, from 0 to 1
let wallX = hit.vertical ? hit.y : hit.x;
wallX -= Math.floor(wallX);
let texture = textures[hit.wall];
let textureX = Math.floor(wallX * texture.width);
context.drawImage(
    texture,
    textureX, 0, 1, texture.height,
    column, top, 1, height
);

This goes in drawWalls(), in place of fillRect() with the blue color. drawImage() with nine arguments takes a rectangle out of an image, and draws it on the canvas at any size you like. Here, that rectangle is one pixel wide and as tall as the texture, and drawImage() stretches it to the height of the wall. The tutorial about images and sprite animations explains the nine arguments. textures is an object with a texture for each kind of wall, and hit.wall, the character in the level, picks one.

A texture can be an image that you load, but you can also draw it in code. In that case, the texture is a small canvas, 16 by 16 pixels, that you never add to the page. You draw on it once, at the start, and after that you use it like an image:

// A texture is a small canvas that the code draws on once
function createTexture(color) {
    let texture = document.createElement('canvas');
    texture.width = 16;
    texture.height = 16;
    let textureContext = texture.getContext('2d');
    textureContext.fillStyle = color;
    textureContext.fillRect(0, 0, 16, 16);
    return texture;
}

function createBrickTexture() {
    let texture = createTexture('#0099b0');
    let textureContext = texture.getContext('2d');
    textureContext.fillStyle = '#006373';
    for (let y = 0; y < 16; y += 4) {
        // The line between two rows of bricks
        textureContext.fillRect(0, y, 16, 1);
        // The lines between two bricks, shifted every other row
        let x = y % 8 == 0 ? 0 : 4;
        textureContext.fillRect(x, y, 1, 4);
        textureContext.fillRect(x + 8, y, 1, 4);
    }
    return texture;
}

let textures = {
    '#': createBrickTexture(),
    'W': createWoodTexture()
};

createWoodTexture() works the same way, with planks instead of bricks. You'll find it in the example code at the end of this page.

A texture this small gets stretched a lot, and the browser blurs it. For sharp pixels, like in old games, set context.imageSmoothingEnabled = false for the canvas on the page, right after you get its context.

In the demo below, turn on Textures to see the bricks, and look for the walls of wooden planks:

Textures

Add sprites with a depth buffer

A game needs more than walls. It also needs things in the maze, like the chili peppers in the demo at the top of this page. Those are sprites: flat images that always face the player, like a cardboard cutout that turns to follow you. In the code, a sprite is an object with an x and a y in the level, like the player.

To draw a sprite, first work out where it is relative to the player, and how big it is:

  • Math.atan2() - Gives you the angle from the player to the sprite. Subtract the player's angle to get the angle from the middle of the view.
  • Math.tan() - Turns that angle into a position on the canvas: the reverse of what Math.atan() did for the rays.
  • Math.hypot() - Gives you the straight-line distance to the sprite. Multiply it by the cosine of the angle for the distance straight ahead, just as you did for the walls.
  • screenDistance - Divide it by that distance, and you have the size of the sprite.

There's one catch. The walls are already on the canvas, and a sprite behind a wall has to stay hidden behind it. So while you draw the walls, store the wall distance for each column in an array. This array is called the depth buffer. To fill it, add depth[column] = distance; to drawWalls(), right after the line that calculates distance. Then draw the sprite column by column, like the walls, and skip every column where the wall is closer than the sprite:

// The distance to the wall in every column of the canvas
let depth = [];

function drawSprite(sprite, image) {
    let dx = sprite.x - player.x;
    let dy = sprite.y - player.y;
    // The angle between the sprite and where the player looks
    let angle = Math.atan2(dy, dx) - player.angle;
    // Keep the angle between -PI and PI
    angle = Math.atan2(Math.sin(angle), Math.cos(angle));
    // The distance straight ahead, just like for the walls
    let distance = Math.hypot(dx, dy) * Math.cos(angle);
    if (distance < 0.2) {
        return;
    }

    let size = screenDistance / distance;
    let centerX =
        canvas.width / 2 + Math.tan(angle) * screenDistance;
    let left = centerX - size / 2;
    let top = (canvas.height - size) / 2;
    let start = Math.max(Math.floor(left), 0);
    let end = Math.min(Math.ceil(left + size), canvas.width);

    context.globalAlpha = 1 - Math.min(distance / fogDistance, 1);
    for (let column = start; column < end; column++) {
        // Skip the columns where a wall is in front of the sprite
        if (depth[column] < distance) {
            continue;
        }
        let imageX =
            Math.floor((column - left) / size * image.width);
        context.drawImage(
            image,
            imageX, 0, 1, image.height,
            column, top, 1, size
        );
    }
    context.globalAlpha = 1;
}

player.angle keeps growing or shrinking as the player turns. So after you subtract it, the angle can end up far outside the range -PI to PI. Math.sin() and Math.cos() give the same result if you add a whole turn to the angle, and Math.atan2() always returns a value between -PI and PI. So the second Math.atan2() brings the angle back into that range: 0 is straight ahead, and the sign tells you whether the sprite is to the left or the right.

A sprite behind the player has a negative distance straight ahead. A sprite closer than 0.2 cells would fill the whole view. drawSprite() skips both. globalAlpha makes the sprite fade into the fog, like the walls.

The chili image is a small canvas, 16 by 16 pixels, like the textures, with the pepper in the bottom half. createChiliImage() in the example code draws it. drawSprite() draws the image as tall as a wall, so the pepper ends up on the floor.

The depth buffer only holds the walls. So with more than one sprite, sort them by their distance to the player, and draw the ones far away first. Then the close ones end up on top, as in drawChilies() in the example code.

In the demo below, there are chili peppers all over the level. Turn Depth buffer off, and you'll see them through the walls:

Depth buffer

Walk through a random maze

Drawing levels by hand takes a while, so let the computer build them. The tutorial about pathfinding has a function, generateMaze(), that builds a random maze with depth-first search. Its walls are whole cells, exactly what a raycaster needs. You'll also find the function in the example code at the end of this page. If you'd like a maze built in a different way, the tutorial about maze generation algorithms has seven more algorithms.

generateMaze() returns an array of arrays, with one character per cell, instead of an array of strings. level[y][x] works the same way for both, so isWall() and castRay() keep working. The difference is that you can change a single character in an array, which you can't do in a string. That's handy for turning some walls into wood, and for making an exit:

level = generateMaze(15, 11);
// Turn some of the walls into wood
for (let y = 1; y < level.length - 1; y++) {
    for (let x = 1; x < level[y].length - 1; x++) {
        if (level[y][x] == '#' && Math.random() < 0.2) {
            level[y][x] = 'W';
        }
    }
}
// The exit is in the wall next to the bottom-right room
let rows = level.length;
let columns = level[0].length;
level[rows - 2][columns - 1] = 'E';
exit = {x: columns - 0.5, y: rows - 1.5};

generateMaze() carves out rooms in the cells where both x and y are odd, and knocks down the walls between them. That's why the maze needs an odd number of columns and rows: then there's a wall all the way around it. A maze of 15 by 11 cells has 7 rooms across and 5 down.

The exit is a wall marked with the letter E in the level, on the right edge of the maze, next to the room in the bottom-right corner. Its texture is a green door. createExitTexture() in the example code draws the door, and textures stores it under 'E'. exit is the middle of that cell. When the player gets close to it, that counts as finding the way out.

The player starts in the top-left room, at 1.5, 1.5, facing an open cell. Five chili peppers go in random rooms, and when the player walks over one, it counts as found:

for (let chili of chilies) {
    if (distanceTo(chili) < 0.5) {
        chili.found = true;
    }
}
if (distanceTo(exit) < 0.8) {
    escaped = true;
}

distanceTo() returns the distance from the player to a chili or the exit, using Math.hypot(). These lines go at the end of update(). The player can't walk into the exit, because it's a wall. The margin in movePlayer() keeps the player at least 0.7 cells from the middle of the exit: half a cell plus 0.2. So anything closer than 0.8 cells counts as close enough.

A small map in the corner helps you find your way: draw the level a second time, with a small square for every cell and a dot for the player, like drawMap() in the example code.

On a phone, there are no arrow keys, so the demo below puts buttons on the canvas after you tap it. The tutorial about keyboard, mouse and touch controls explains how to add touch buttons to a canvas. Here's the whole game: find the exit and pick up as many chilies as you can on the way, or click New maze to start over:

Common questions about raycasting

Is raycasting the same as ray tracing?

No, but they're related. A raycaster sends one ray per column of the screen, and each ray stops at the first wall it hits. Ray tracing sends at least one ray per pixel, and when a ray hits something, it bounces off to find out how much light reaches that point. That gives you reflections and shadows, but it takes far more work for each frame. Games have only done it in real time since graphics cards got special hardware for it, around 2018.

Was Doom made with raycasting?

No. Doom came out in 1993, a year after Wolfenstein 3D, and draws its levels in a different way, with a binary space partitioning tree. That's why Doom can have stairs, windows and rooms of different heights, which a raycaster like the one in this tutorial can't draw.

How do I look up and down?

Move the horizon. Everything in this tutorial is centered on the middle of the canvas: the walls, the sprites and the border between the ceiling and the floor. Add an offset to that middle, and the whole view shifts up or down. This trick isn't real 3D. If you move the horizon a lot, the view looks stretched, but for looking up or down a little, it works well. Duke Nukem 3D did the same thing.

Can walls have different heights?

Not with the raycaster in this tutorial, because a ray stops at the first wall it hits. For walls of different heights, let the ray keep going after the first hit, and draw the walls behind that one too, from far to near. Then a tall wall far away can rise above a low wall up close. It's possible, but the code gets a lot bigger.

How do I add a textured floor and ceiling?

That's called floor casting. Instead of drawing a gradient, you work out how far away the floor is for every row of pixels below the horizon. Then, for each pixel in that row, you find the spot on the floor texture it shows. Drawing pixel by pixel with fillRect() is far too slow for that, so you write the pixels into an ImageData object instead, and put it on the canvas once per frame. The second part of Lode Vandevenne's tutorial explains how, in C++.

How do I add doors that open?

Give doors their own letter in the level, and for each door, store how far open it is, from 0 to 1. When a ray enters a door cell, work out where it crosses the line through the middle of that cell. If the door still covers that spot, the ray hits the door there, halfway into the cell. If not, the ray goes on into the next cell. Shift the texture by how far the door is open, and the door slides to the side, like the doors in Wolfenstein 3D.

How do I add enemies that chase the player?

An enemy is a sprite that moves. To find its way to the player through the maze, it can search the level grid with breadth-first search or A*. The tutorial about pathfinding algorithms shows both, on the same kind of level as in this tutorial.

How do I look around with the mouse?

Use the Pointer Lock API. After you call canvas.requestPointerLock() in a click event handler, the mouse pointer disappears and can't leave the canvas. From then on, the movementX property of every mousemove event tells you how far the mouse moved sideways. Multiply it by a small number such as 0.003, add it to the player's angle, and the player turns with the mouse. Press Escape to get the pointer back.

Why is my raycaster slow?

If your rays still take small steps, switch to DDA first. After that, the slow part is usually the drawing, not the rays. A canvas 750 pixels wide means 750 calls to drawImage() or fillRect() for every frame, plus the shading. If your game is too slow, cast one ray for every two columns and draw strips two pixels wide, which halves the work. For the best speed, write all the pixels into one ImageData object and draw that once per frame.

What does raycasting mean in Unity or Roblox?

Something different, with the same idea behind it. In game engines like Unity, Godot and Roblox, a raycast is a ray you send from one point into the 3D world, to find out what it hits first. Games use it to check if a bullet hits an enemy, if the player stands on the ground, or if an enemy can see the player. It answers the same question as the rays in this tutorial, but for the game logic instead of for drawing walls.

Example code: a raycaster

Here's an example page that puts everything from this tutorial together in a single HTML file: a random maze with walls of brick and wood, five chili peppers to find, a map in the corner and a green door as the exit.

Click the canvas, and walk with the arrow keys or WASD. The canvas has tabindex="0", so it gets keyboard focus when you click it. When you've found the way out, press Space for a new maze. The example code only works with a keyboard, so for a phone, you'd need to add touch buttons.

Paste the code below into an HTML file and open it in your browser:

Conclusion

A raycaster draws a 3D maze from a 2D grid, with one ray for every column of the canvas. DDA finds the wall each ray hits, one grid line at a time. The distance straight ahead, which avoids the fisheye effect, determines how tall the wall is. On top of that come shading, textures and sprites, with a depth buffer so the walls hide the sprites behind them.

From here, you can turn the maze into a real game. Add enemies that find their way to the player with pathfinding, doors that slide open, or a floor with a texture. The questions above give you a head start on each of them.

That's all for now. If you have any questions, feel free to ask them in the comment section. You can