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