1

I'm working on a JavaScript canvas API using an Object Oriented approach. My problem is that after using requestAnimationFrame in the animate method I get this as undefined. If I remove the requestAnimationFrame from the animate method the errors goes away - Any idea how to solve this?

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);
  }
}

app.js

import Canvas from "./Canvas";

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

const obj = new Canvas(c, ctx);

obj.animate();
chazsolo
  • 7,873
  • 1
  • 20
  • 44
MUHAMMAD Siyab
  • 436
  • 1
  • 9
  • 20
  • Does this answer your question? [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – Belmin Bedak Jan 13 '20 at 15:32

1 Answers1

3

You might need to bind the methods to use this.

Try the below code for 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);
  }
}
Nikhil Goyal
  • 1,945
  • 1
  • 9
  • 17