i have this code:
export default class Main {
canvas: HTMLCanvasElement | null;
context: CanvasRenderingContext2D | null;
constructor() {
this.canvas = null;
this.context = null;
}
init() {
this.canvas = <HTMLCanvasElement>document.getElementById('canvas');
this.context = this.canvas.getContext('2d');
window.requestAnimationFrame(this.gameLoop);
return () => { };
}
draw() {
const randomColor = Math.random() > 0.5 ? '#ff8080' : '#0099b0';
this.context.fillStyle = randomColor;
this.context.fillRect(100, 50, 200, 175);
}
// eslint-disable-next-line no-unused-vars
gameLoop(timestamp: number) {
this.draw();
window.requestAnimationFrame(this.gameLoop);
}
core() {
window.onload = this.init();
}
}
const main = new Main();
main.core();
the error i receive is: [Error] TypeError: undefined is not an object (evaluating 'this.draw') gameLoop (main.ts:19)
but actually if I log this
inside gameLoop i get undefined
which makes sense because gameLoop is called innerly by requestAnimationFrame, not by my Main
class.
and because of the same problem, this.draw
is undefined.
how to fix that?