I've implemented an rAF(requestAnimationFrame) setup for my game loop:
draw: function (x, y) {
setTimeout(function () {
requestAnimationFrame(function() {
Player.draw(150, 150);
});
//drawing code: worked perfectly with setInterval
}, 1000 / 60);
},
It's in a Player
object, in a draw
function. I call:
Player.draw(Player.x, Player.y);
at the bottom of the code.
From what I've seen on similar questions, the images need to be declared before this is evaluated. I have loaded my images at the top using an immediately called function:
var images = [];
x = 0;
(function() {
for (let i = 0; i < 20; i++) {
images[i] = new Image();
images[i].src = ('../webgame/assets/images/survivor-idle_shotgun_' + i + '.png');
};
})(); // This worked perfectly with setInterval too
However I get this error:
Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '(CSSImageValue or HTMLImageElement or SVGImageElement or HTMLVideoElement or HTMLCanvasElement or ImageBitmap or OffscreenCanvas)'
it points to this line of code:
ctx.drawImage(images[this.spriteCostumeCount], this.x, this.y, this.width, this.height);
in the drawing code.
How can I get the player sprite to be animated using this requestAnimationFrame and how can I fix this error?