New to Rust? Grab our free Rust for Beginners eBook Get it free →
JavaScript Snake Game With Canvas

Making a Snake game in JavaScript means updating the board as the snake moves. The game uses grid positions, timed ticks, and an HTML canvas to move and draw the snake.
You’ll see how to write the code for movement and food placement. The article also explains how the game checks collisions and grows the snake.
TL;DR
A JavaScript Snake game stores grid positions, advances the snake on timed ticks, and redraws each state on a canvas.
- Put the head at index zero in a snake array.
- Reject reverse turns, check collisions, then draw.
- On food, keep the tail and choose an unoccupied cell.
What Is a JavaScript Snake Game?
A Snake game in JavaScript moves a chain of cells and paints the board on an HTML canvas. The play area has a fixed width and height. Each move changes the head by one cell.
CSS sets the page layout, while CanvasRenderingContext2D paints the board and its pieces. The score display changes when the snake eats.
A position uses an x and y pair, such as x equals 10 and y equals 10. The 20-pixel cell size sets the board resolution.
Eating adds a segment and raises the displayed score. The reset values are listed with the other boundary rules below. The game can stop on a wall or body collision.
How to Build a JavaScript Snake Game Step by Step
Use one canvas for the board. The game below redraws it after the state changes on each tick.
Step 1: Create the board and game state
Add a canvas and a score label. Store positions as grid coordinates rather than pixels, then multiply by the cell size only when drawing.
<canvas id="board" width="400" height="400"></canvas>
<p>Score: <span id="score">0</span></p>
<script>
const canvas = document.querySelector('#board');
const ctx = canvas.getContext('2d');
const cell = 20, cells = canvas.width / cell;
let snake = [{x: 10, y: 10}, {x: 9, y: 10}, {x: 8, y: 10}];
let direction = {x: 1, y: 0}, queued = direction;
let food = {x: 14, y: 10}, score = 0, last = 0;
const scoreEl = document.querySelector('#score');
Step 2: Read turns without allowing reversal
Queue a legal turn and apply it at the next tick. Comparing vectors prevents an immediate 180-degree turn into the snake’s neck.
document.addEventListener('keydown', (event) => {
const turns = {
ArrowUp: {x: 0, y: -1}, ArrowDown: {x: 0, y: 1},
ArrowLeft: {x: -1, y: 0}, ArrowRight: {x: 1, y: 0}
};
const next = turns[event.key];
if (next) {
event.preventDefault();
if (next.x !== -direction.x || next.y !== -direction.y) queued = next;
}
});
Step 3: Advance one grid cell per tick
Calculate the next head before changing the array. Check walls and the body before inserting it. Remove the tail only when food was not eaten.
function tick() {
direction = queued;
const head = {x: snake[0].x + direction.x, y: snake[0].y + direction.y};
const ate = head.x === food.x && head.y === food.y;
const body = ate ? snake : snake.slice(0, -1);
const hit = head.x < 0 || head.y < 0 || head.x >= cells || head.y >= cells ||
body.some(part => part.x === head.x && part.y === head.y);
if (hit) return false;
snake.unshift(head);
if (ate) { score++; scoreEl.textContent = score; placeFood(); }
else snake.pop();
return true;
}
Step 4: Place food and draw every state
Food placement needs to account for the board size. Redraw after a successful tick. The drawing function paints the background before the snake and food.
function placeFood() {
const free = [];
for (let y = 0; y < cells; y++) for (let x = 0; x < cells; x++)
if (!snake.some(part => part.x === x && part.y === y)) free.push({x, y});
food = free[Math.floor(Math.random() * free.length)];
}
function draw() {
ctx.fillStyle = '#111827'; ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = '#22c55e';
snake.forEach(part => ctx.fillRect(part.x * cell, part.y * cell, cell - 1, cell - 1));
ctx.fillStyle = '#ef4444'; ctx.fillRect(food.x * cell, food.y * cell, cell - 1, cell - 1);
}
function loop(time) {
if (time - last > 120) { last = time; if (!tick()) return; }
draw(); requestAnimationFrame(loop);
}
requestAnimationFrame(loop);
I ran node snake_demo.js to check the food-eating tick. Its output was:
head=(4,2) length=4 ate=true wallCollision=false bodyCollision=false

The head advances onto food, and the length rises from three to four because the tail stays in place. The check also confirms that this move crosses neither a wall nor the body.
Edge Cases to Handle
Input timing and update order cause the common Snake bugs. Test these cases before adding animation or extra features. A useful check is to follow one proposed head position through bounds, occupancy and array updates in that order.
Reset restores the starting snake and direction, places food in a free cell, and sets the score back to zero.
| Case | Symptom | Fix |
|---|---|---|
| Reverse turn | Head overlaps neck | Reject opposite vector |
| Tail cell | False collision when tail moves away | Exclude departing tail if not eating |
| Food on snake | Food appears hidden | Pick among free cells |
| Wall bound | Head partly leaves grid | Compare cell index with cells – 1 |
The tail collision exception follows the growth rule. When no free food cell remains, handle the empty result as a win rather than indexing an empty array.
The animation callback runs once per request, so the loop schedules another frame after drawing. Hidden tabs may pause callbacks, which can slow a game that advances only on those frames.
Conclusion
Keep input, movement, collision and rendering separate so each tick has a clear order. The tick probe printed head=(4,2), length=4 and ate=true.
For more browser projects, see CodeForGeek’s alarm clock tutorial and calculator project. MDN’s Canvas animation guide explains drawing callbacks, and its requestAnimationFrame reference covers frame scheduling.
FAQ
These answers cover setup choices that affect the first playable version.
Can I make Snake with plain JavaScript?
Yes. HTML provides the canvas and JavaScript handles state, input, movement and drawing without a game library.
Why use a grid for Snake?
A grid uses integer cell coordinates for the snake and food, with pixel conversion applied by the drawing code.
How do I make the snake grow?
Keep the tail segment after the head reaches food; on other ticks remove the tail after inserting the new head.




