'this' не определено в методе класса с requestAnimationFrame - PullRequest
0 голосов
/ 13 января 2020

Я работаю над JavaScript API холста, используя объектно-ориентированный подход. Моя проблема в том, что после использования requestAnimationFrame в методе animate я получаю this как неопределенное. Если я уберу requestAnimationFrame из animate метода, ошибки исчезнут - Есть идеи, как это решить?

Canvas. js

export default class Canvas {
  constructor(canvas, ctx) {
    this.canvas = canvas;
    this.ctx = ctx;
    this.x = 100;
    this.y = 100;
    this.dx = 4;
    this.dy = 5;
    this.canvas.width = window.innerWidth;
    this.canvas.height = window.innerHeight;
  }

  drawCircle(x, y) {
    for (let i = 0; i < 6; i++) {
      this.ctx.beginPath();
      this.ctx.fillStyle = "lightblue";
      this.ctx.arc(x, y, 30, 0, Math.PI * 2);
      this.ctx.fill();
    }
  }

  animate() {
    // Clear rect
    this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);

    requestAnimationFrame(this.animate);

    this.x += 1;

    this.drawCircle(this.x, this.y);
  }
}

приложение. js

import Canvas from "./Canvas";

let c = document.getElementById("canvas");
let ctx = c.getContext("2d");

const obj = new Canvas(c, ctx);

obj.animate();

1 Ответ

2 голосов
/ 13 января 2020

Вам может понадобиться связать методы, чтобы использовать это.

Попробуйте приведенный ниже код для Canvas. js

export default class Canvas {
  constructor(canvas, ctx) {
    this.canvas = canvas;
    this.ctx = ctx;
    this.x = 100;
    this.y = 100;
    this.dx = 4;
    this.dy = 5;
    this.canvas.width = window.innerWidth;
    this.canvas.height = window.innerHeight;
    
    this.drawCircle = this.drawCircle.bind(this);
    this.animate = this.animate.bind(this);
  }

  drawCircle(x, y) {
    for (let i = 0; i < 6; i++) {
      this.ctx.beginPath();
      this.ctx.fillStyle = "lightblue";
      this.ctx.arc(x, y, 30, 0, Math.PI * 2);
      this.ctx.fill();
    }
  }

  animate() {
    // Clear rect
    this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);

    requestAnimationFrame(this.animate);

    this.x += 1;

    this.drawCircle(this.x, this.y);
  }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...