【发布时间】:2021-01-15 14:23:29
【问题描述】:
const canvas = document.getElementById("canvas");
canvas.width = canvas.height = 700;
const h = canvas.height;
const w = canvas.height;
const ctx = canvas.getContext("2d");
const snake = {
width: w / 12,
height: h / 12,
blocks: [[40, 30, this.width, this.height]],
renderSnake() {
this.blocks.forEach((b) => {
ctx.fillStyle = "black";
ctx.fillRect(...b);
console.log(this.blocks);
});
console.log(this.blocks);
},
};
在我的代码中,问题出在蛇对象的 blocks 属性中。 this.width 和 this.height 是未定义的,我添加了一些 console.log 并意识到 blocks 数组属性中的 this 关键字指向 Window 对象,我如何使它指向蛇对象或在没有硬编码的情况下使其工作宽度和高度。
【问题讨论】:
-
如果你想让
blocks是动态的,它应该是一个函数
标签: javascript canvasjs