Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
28
rated 0 times [  30] [ 2]  / answers: 1 / hits: 26067  / 5 Years ago, fri, august 2, 2019, 12:00:00

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?


More From » javascript

 Answers
51

You need to make sure that images[this.spriteCostumeCount] is defined and of the correct type.



An easy way to test this would be to add a console.log(typeof images[this.spriteCostumeCount]) right before you call the drawImage method.



If the result is undefined, you can encapsulate the call in a if condition. If it is defined, make the it is a type that is accepted by the drawImage method.


[#51807] Saturday, July 27, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
keana

Total Points: 452
Total Questions: 97
Total Answers: 81

Location: Barbados
Member since Sun, Nov 27, 2022
2 Years ago
;