我收到以下错误:
Uncaught TypeError: Cannot read property 'x' of undefined at draw (app.js:68)
第 68 行是 let SnakeX = Snake[0].x;
。这是我的代码:
const cvs = document.getElementById('canvas');
const ctx = cvs.getContext('2d');
// create the unit
const box = 32;
// load img / audio
let ground = new Image();
ground.src = "img/ground.png";
const foodImg = new Image();
foodImg.src = "img/food.png"
// creat the snake
let snake = [];
snake[0] = {
x: 9 * box,
y: 10 * box
};
// create the food
let food = {
x: Math.floor(Math.random() * 17 + 1) * box,
y: Math.floor(Math.random() * 15 + 3) * box
}
// create the score var
let score = 0;
// control the snake
let d;
document.addEventListener("keydown", direciton);
function direciton(event) {
if (event.keyCode == 37) {
d = "LEFT";
} else if (event.keyCode == 38) {
d = "UP";
} else if (event.keyCode == 39) {
d = "RIGHT";
} else if (event.keyCode == 40) {
d = "DOWN";
}
}
// draw everything to the canvas
function draw() {
ctx.drawImage(ground, 0, 0);
for (let i = 0; i < snake.length; i++) {
ctx.fillStyle = (i == 0) ? "green" : "white";
ctx.fillRect(snake[i].x, snake[i].y, box, box);
ctx.strokeStyle = "red";
ctx.strokeRect(snake[i].x, snake[i].y, box, box);
}
ctx.drawImage(foodImg, food.x, food.y);
//old head position
let snakeX = snake[0].x;
let snakeY = snake[0].y;
//which direction
if (d = "LEFT") snakeX -= box;
if (d = "UP") snakeY -= box;
if (d = "RIGHT") snakeX += box;
if (d = "DOWN") snakeY += box;
//remove the tail
snake.pop();
// add new Head
let newHead = {
x: snakeX,
y: snakeY
}
ctx.fillStyle = "white";
ctx.font = "45px Changa one";
ctx.fillText(score, 2 * box, 1.6 * box);
}
// call draw function every 100ms
let game = setInterval(draw, 100);
最佳答案
您忘记将对象 newHead 添加到您的蛇数组中。
您需要添加:
snake.push(newHead)
定义之后。
关于javascript - Canvas - 无法读取未定义的属性 'x',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59292408/