首页 > 解决方案 > 如何为游戏循环进行类方法递归?

问题描述

我有这个代码:

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 is not an object (evalating 'this.draw') gameLoop (main.ts:19)

但实际上,如果我this在 gameLoop 中登录,我会明白undefined这是有道理的,因为 gameLoop 是由 requestAnimationFrame 内部调用的,而不是由我的Main班级调用的。并且由于同样的问题,this.draw是未定义的。

如何解决?

标签: javascriptclassooprecursion

解决方案


您需要将该方法绑定到您的类以确保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>


推荐阅读