如何使类方法递归游戏循环



我有这个代码:

export default class Main {
canvas: HTMLCanvasElement | null;
context: CanvasRenderingContext2D | null;
constructor() {
this.canvas = null;
this.context = null;
}
init() {
this.canvas = <HTMLCanvasElement>document.getElementById('canvas');
this.context = this.canvas.getContext('2d');
window.requestAnimationFrame(this.gameLoop);
return () => { };
}
draw() {
const randomColor = Math.random() > 0.5 ? '#ff8080' : '#0099b0';
this.context.fillStyle = randomColor;
this.context.fillRect(100, 50, 200, 175);
}
// eslint-disable-next-line no-unused-vars
gameLoop(timestamp: number) {
this.draw();
window.requestAnimationFrame(this.gameLoop);
}
core() {
window.onload = this.init();
}
}
const main = new Main();
main.core();

我收到的错误是:[Error]TypeError:undefined不是对象(正在计算"this.draw"(gameRoop(main.ts:19(

但实际上,如果我在gameRoop中记录this,我会得到undefined,这是有意义的,因为gameRoops是由requestAnimationFrame内部调用的,而不是由我的Main类调用的。并且由于同样的问题,this.draw是未定义的。

如何修复?

您需要将方法绑定到您的类,以确保this指向您的类。

class Main {
canvas;
context;

init() {
this.canvas = document.getElementById('canvas');
this.context = this.canvas.getContext('2d');
window.requestAnimationFrame(this.gameLoop.bind(this));
}
draw() {
const randomColor = Math.random() > 0.5 ? '#ff8080' : '#0099b0';
this.context.fillStyle = randomColor;
this.context.fillRect(100, 50, 200, 175);
}

gameLoop(timestamp) {
this.draw();

window.requestAnimationFrame(this.gameLoop.bind(this));
}
core() {
window.onload = this.init();
}
}
const main = new Main();
main.core();
<canvas id="canvas"></canvas>

相关内容

  • 没有找到相关文章

最新更新