It’s better to load all animations sprites in a array before start or do this that also works fine too:
var frame = new Image(); function update(){ window.requestAnimationFrame(update); ctx.drawImage(frame, x, y, width, height) } window.addEventListener("keydown", key => { if(key.keyCode == 65 || key.keyCode == 37){ for(var i = 0; i <= 3; i++){ frame.src = "./walkingspriteframes/frame"+i+".png"; }; } })
Advertisement
Answer
Preloading is usually the best thing to do (at least for frequently used assets, such as animation sprites), for these reasons:
- Fetching resources over a network has a latency cost associated with it. When you are doing it during a game that should be running at 30-60 frames per second and responding to user inputs quickly, it may significantly degrade the player’s experience.
- If you are loading images on demand, you will need to consider the possibility that the image loading may fail (because of a network failure, for example) and what should be done in such a situation. An advantage of preloading is that you can choose to not let your game start if important assets are not available.
In addition, the code you have posted will not work as you may have expected it to. It will only display frame3.png
. This is because JavaScript in the browser is single-threaded: update
and the keydown listener will never run concurrently, so the ctx.drawImage
call in update
will not see frame.src
set to frame1.png
or frame2.png
.