一、设置画布(游戏范围)
画布
<canvas width="400" height="400"></canvas>
画布样式
<style>canvas {border: 1px solid black;}</style>
二、游戏逻辑
// 设置画布和绘图环境const canvas = document.getElementById("canvas");const ctx = canvas.getContext("2d");// 定义贪吃蛇和食物的初始位置let snake = [{ x: 200, y: 200 }];let food = { x: 0, y: 0 };// 定义贪吃蛇的方向let direction = "right";// 生成食物的函数function generateFood() {food.x = Math.floor(Math.random() * canvas.width / 10) * 10;food.y = Math.floor(Math.random(