我看到这个问题以前被问过,但它并没有解决我的问题!我是 JavaScript 新手,我几乎花了一天时间尝试解决它,但仍然无法解决。
我有一个这样的类和函数:
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();
这是我的问题!当我单击该键时,我会收到以下错误:
can't read property 'clearRect' of undefined
can't read property 'draw' of undefined
我实在不明白为什么不能访问同一个类中的属性和函数?
蝴蝶刀刀
相关分类