javascipt "Cannot read property 'height' of undefined" error



我是javascript的新手,我试图开发一个新游戏,但我收到了这个消息,我不明白为什么。我很高兴得到你的帮助!(错误发生在"this.top=(Math.random((*cvs.height(/3+20"行(。

const obstablesArray = [];
class Obstable {
constructor(cvs) {
this.top = (Math.random() * cvs.height) / 3 + 20;
this.bottom = (Math.random() * cvs.height) / 3 + 20;
this.x = cvs.width;
this.width = 20;
this.color = "red";
this.cvs = cvs;
}
draw(ctx) {
ctx.fillStyle = this.color;
ctx.fillRect(this.x, 0, this.width, this.top);
ctx.fillRect(
this.x,
this.cvs.height - this.bottom,
this.width,
this.bottom
);
}
update(gameSpeed) {
this.x -= gameSpeed;
this.draw();
}
}
export function handleObstacle(bird, ctx, frame) {
if (frame % 50) obstablesArray.unshift(new Obstable());
for (let i = 0; i < obstablesArray.length; i++) {
obstablesArray[i].update(this.ctx);
}
if (obstablesArray.length > 20)
for (let i = 0; i < 20; i++) {
obstablesArray.pop(obstablesArray[0]);
}
}

我创建了这个类的简历并发送:

import Bird from "/src/bird";
import { handleObstacle } from "./obstacles";
const cvs = document.getElementById("canvas1");
const ctx = cvs.getContext("2d");
cvs.width = 600;
cvs.height = 400;
let frame = 0;
let spacePress = false;
let angle = 0;
const bird = new Bird();
function animate() {
ctx.clearRect(0, 0, cvs.width, cvs.height);
bird.update(cvs, spacePress, angle);
bird.draw(ctx);
//handleParticiles(bird, ctx);
handleObstacle(bird, ctx, frame);

这是因为您没有在这里将cvs传递给类构造函数:

export function handleObstacle(bird, ctx, frame) {
if (frame % 50) obstablesArray.unshift(new Obstable()); //<-- here
...
}

当然,cvs是未定义的。

相关内容

最新更新