I've encountered a similar question before, but unfortunately, the solution provided didn't help me! I'm relatively new to JavaScript and have been struggling with this issue for nearly a day now without success.
The structure of my class and function is as follows:
let playerTank = {width: 80, height: 80, speed: 2};
class Tank {
constructor(canvas) {
this.canvas = canvas;
this.ctx = canvas.getContext("2d");
}
draw() {
this.ctx.drawImage(.....);
this.ctx.stroke();
}
update(e) {
if (e.keyCode == 37) {
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
this.draw();
// do something ...
}
}
}
function main() {
let canvas = document.getElementByID("my-canvas");
let tank = new Tank(canvas);
tank.draw();
window.addEventListener("keydown", tank.update, true);
window.addEventListener("keyup", tank.update, false);
}
main();
My issue arises when I try to interact with the keys, as I'm encountering the following errors:
can't read property 'clearRect' of undefined
can't read property 'draw' of undefined
I am perplexed as to why I am unable to access the attributes and functions within the same class. Can someone please provide guidance on how to resolve this?