javascript - Canvas - 无法读取未定义的属性 'x'

标签 javascript

我收到以下错误:

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/

相关文章:

javascript - 在 AngularJS 中格式化 float 而不损失精度

JavaScript "This"脱离上下文,而是指窗口

javascript - SharePoint 2010 - 内容编辑器 Web 部件复制条目

javascript - Vee-validate 无法使用 Nuxt.js 和 Vuetify 处理范围

javascript - 使用 javascript 和 vue 将对象添加到数组时我应该怎么做?

javascript - jQuery,添加可拖动以追加对象

javascript - 在 `Focusout` true 上的表 td 上使用 `contenteditable = "

javascript - 如果没有 jQuery,我如何有选择地删除数组中存在的元素?

javascript - 根据用户输入从表中删除行

javascript - HTML5 Canvas 上的多点/颜色渐变