簡體   English   中英

在類中使用requestAnimationFrame

[英]Using requestAnimationFrame in a class

當我在類中使用requestAnimationFrame時,不會返回常規this

我一直在尋找有關該主題的所有帖子(試圖將step()函數封裝為一個帶有動畫效果的匿名函數...),但是我仍然遇到同樣的問題。

class Sprite {

  constructor(canvas, imageSrc) {
    this.canvas = canvas;
    this.img = new Image();
    this.img.src = imageSrc;
    this.height = 18;
    this.width = 16;
    this.scale = 4;
    this.scaledWidth = this.scale * this.width;
    this.scaledHeight = this.scale * this.height;
    this.cycleLoop = [0];
    this.currentLoopIndex = 0;

    this.img.onload = () => {
      this.init();
    }
  }

  init() {
    this.ctx = this.canvas.getContext('2d');
    this.ctx.webkitImageSmoothingEnabled = false;
    this.ctx.mozImageSmoothingEnabled = false;
    this.ctx.imageSmoothingEnabled = false;
  }

  drawFrame(frameX, frameY, canvasX, canvasY) {
    this.ctx.drawImage(
      this.img,
      frameX * this.width,
      frameY * this.height,
      this.width,
      this.height,
      canvasX,
      canvasY,
      this.scaledWidth,
      this.scaledHeight
    );
  }

  animate() {
    requestAnimationFrame(this.step());
  }

  step() {
    console.log(this);
    console.log(this.ctx);
    this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);

    this.drawFrame(this.cycleLoop[this.currentLoopIndex], 0, 0, 0);
    this.currentLoopIndex++;


    if (this.currentLoopIndex >= this.cycleLoop.length) {
      this.currentLoopIndex = 0;
    }
    requestAnimationFrame(this.step());
  }
}

step() ,第一個console.log(this)顯示具有ctx屬性的Character對象。 由於某些原因,未定義第二個console.log(this.ctx)

所以我得到:

Uncaught TypeError: Cannot read property 'clearRect' of undefined
    at Character.step (sprite.js:49)
this.canvas = canvas;

在Sprite類的構造函數中定義。

this.ctx = this.canvas.getContext('2d');

但是在Image的onload事件的回調函數中定義。 所以我最好的猜測是,當您在Sprite實例上調用animate()方法時,onload事件並未觸發,因此上下文尚未定義。

似乎在定義ctx之前正在調用step() 最有可能的,因為step()是在之前稱為img.onload()它創建回調ctx

確保在init()之后調用step() init()

或在constructor設置ctx ,方法如下:

this.ctx = canvas.getContext('2d');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM