0

I am trying to create this class Animator that I use to repeatedly draw on a canvas. It is simple enough.

The class is initialized with a canvas 2D context. The private method #update is responsible to draw things on the canvas. It will invoke itself by using requestAnimationFrame.

The start and stop methods are supposed to start and stop the animation by use of requestAnimationFrame and cancelAnimationFrame.

However, I am getting this error: Uncaught TypeError: Cannot read properties of undefined (reading '#ctx')

I am not exactly sure what I am doing wrong. I think it has to do something with passing this.#update as a callback to requestAnimationFrame/cancelAnimationFrame, but I cannot quite figure it out.

Could someone please help me and tell me what I am doing wrong?

class Animator {
  #ctx;
  #requestId;
  
  constructor(ctx) {
    this.#ctx = ctx;
    this.#ctx.fillStyle = 'black';
  }
  
  #update() {
    this.#ctx.fillRect(10, 10, 10, 10);    
    this.#requestId = requestAnimationFrame(this.#update);
  }
  
  run() {
    this.#requestId = requestAnimationFrame(this.#update);
  }
  
  pause() {
    if (this.#requestId) {
      cancelAnimationFrame(this.#requestId);
    }
    
    this.#requestId = null;
  }
}

const ctx = document.getElementById('c');
const test = new Animator(ctx);
test.run();
<canvas id="c" width="100" height="100"></canvas>
sampathsris
  • 21,564
  • 12
  • 71
  • 98
  • 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) or [requestAnimationFrame with this keyword](https://stackoverflow.com/questions/6065169/requestanimationframe-with-this-keyword) – Ivar Sep 01 '22 at 07:42
  • 1
    @Ivar Yes, it did. Can't imagine why I missed that question. This question needs to close. – sampathsris Sep 01 '22 at 07:46

0 Answers0