JSFiddle - React, Tailwind, and code Playground
by replicateur
HTML
<canvas id="canvas" width="360px" height="360px"></canvas>
CSS
canvas {
border: 1px solid black;
}
JavaScript
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
// Set canvas size to window size
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// Set initial snake position
let snake = [{x: canvas.width / 2, y: canvas.height / 2}];
// Set initial snake velocity
let dx = 10;
let dy = 0;
// Set initial food position
let food = {x: Math.floor(Math.random() * canvas.width), y: Math.floor(Math.random() * canvas.height)};
// Set snake movement interval
let interval = setInterval(update, 100);
// Update function to update snake position and draw everything on the canvas
function update() {
// Update snake position
let head = {x: snake[0].x + dx, y: snake[0].y + dy};
snake.unshift(head);
// Check if snake ate the food
if (snake[0].x === food.x && snake[0].y === food.y) {
// Generate new food
food = {x: Math.floor(Math.random() * canvas.width), y: Math.floor(Math.random() * canvas.height)};
} else {
// Remove the tail of the snake
snake.pop();
}
// Clear canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw food
ctx.fillStyle = "red";
ctx.fillRect(food.x, food.y, 10, 10);
// Draw snake
ctx.fillStyle = "green";
for (let i = 0; i < snake.length; i++) {
ctx.fillRect(snake[i].x, snake[i].y, 10, 10);
}
}
// Set keydown event to change snake direction
document.addEventListener("keydown", event => {
if (event.key === "ArrowLeft") {
dx = -10;
dy = 0;
} else if (event.key === "ArrowRight") {
dx = 10;
dy = 0;
} else if (event.key === "ArrowUp") {
dx = 0;
dy = -10;
} else if (event.key === "ArrowDown") {
dx = 0;
dy = 10;
}
});