簡體   English   中英

'this' 在帶有 requestAnimationFrame 的類方法中未定義

[英]'this' is undefined in class method with requestAnimationFrame

我正在使用面向對象的方法處理 JavaScript 畫布 API。 我的問題是,在animate方法中使用requestAnimationFrame ,我將this設為未定義。 如果我從animate方法中刪除requestAnimationFrame錯誤就會消失 - 知道如何解決這個問題嗎?

畫布.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();

您可能需要綁定方法才能使用它。

試試下面的 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); } }

暫無
暫無

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

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