我使用 JavaScript 中的 animate
方法创建了这个 class Cars
。我想创建一个汽车原型(prototype)。当我尝试调用该方法时,我不断收到:
TypeError: 无法读取 'animate' 的 null 属性 'carTag'
我试图理解为什么我不断收到此错误。
class Cars{
constructor(carTag){
//sets up the local variables for the constructor function
this.carTag = new Image()
this.carTag.src = carTag
document.getElementById("gameboard").innerHTML =
this.carTag
}
animate() {
const image = this.carTag;
const animate = this.animate;
let throttle = 2000;
const canvas = document.getElementById("gameboard");
const ctx = canvas.getContext("2d");
let x = canvas.width;
let y = 0;
setTimeout (function(){
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(image, x, y);
x -=4;
requestAnimationFrame(animate);
}, 1000/throttle);
}
}
car1 = new Cars("http://i.stack.imgur.com/Rk0DW.png");
car1.animate();
感谢您的帮助!
更新: 错误是由 requestAnimationFrame(动画);
我想弄清楚为什么我不能通过这个循环传递图像。
感谢您的帮助。我真的很感激。
最佳答案
class Cars{
constructor(carTag){
//sets up the local variables for the constructor function
this.carTag = carTag
}
...
}
进行此更改,它将起作用。你的 carTag 是 imgTag
--------------------------------编辑------------ --------------------------------
图像传递正确
首先图像已经在窗口对象中所以它已经是全局的
class Cars{
constructor(carTag){
//sets up the local variables for the constructor function
this.carTag = new Image()
this.carTag.src = carTag
document.getElementById('abcd').innerHTML = this.carTag
}
animate() {
const image = this.carTag;
const animate = this.animate;
let throttle = 2000;
setTimeout (function(){
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(image, x, y);
x -=4;
requestAnimationFrame(animate);
}, 1000/throttle);
}
}
car1 = new Cars("http://i.stack.imgur.com/Rk0DW.png")
this.carTag 是一个图像对象。 希望这会有所帮助。
关于javascript - 类型错误 : cannot read property variable of null of a method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50976497/