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>