После прочтения некоторых решений я придумал следующее:
class Car{
constructor(carTag, throttle, yPosition){
this.carTag = carTag
this.carTag = new Image()
this.throttle = throttle
this.yPosition = yPosition
}
//Animate method that will animate cars across the screen
animate(){
const ref = this;
requestAnimationFrame(function(){
ref.animate();
});
const canvas = document.getElementById("gameboard");
const ctx = canvas.getContext("2d");
let xPosition = canvas.width;
setTimeout (function(){
ctx.clearRect(0, 0, xPosition, ref.yPosition);
ctx.drawImage(ref.carTag, xPosition, ref.yPosition);
xPosition -= 4;
console.log(xPosition);
}, 1000/ref.throttle);
}
}
const cars = new Car;
cars.carTag.src = "http://i.stack.imgur.com/Rk0DW.png";
cars.throttle = 2000;
cars.yPosition = 0;
cars.animate();
Проблема, с которой я все еще сталкиваюсь, заключается в том, почему мой автомобиль застрял в одной позиции, а не анимировался. Почему bind (this) мешает requestAnimationFrame?
обновление: последняя версия этого метода не выдает сообщения об ошибках. Но по какой-то причине xPosition не обновляется, что перемещает изображение автомобиля влево. Я попытался поместить requestAnimationFrame в конец метода, тот же результат.