Answer the question
In order to leave comments, you need to log in
How can I optimize frame-by-frame animation on Canvas in JS?
There is a JS script, where there is an array of Image objects already loaded (PNG format animation frames), and there is a canvas.
There is also a function that clears the canvas (clearRect) and then draws the next frame from the array using drawImage .
The problem is that if you take two (or more) canvases with frame-by-frame animation and play them at the same time, severe FPS drops begin.
Are there any ways to optimize such animations so that they spend less resources and, accordingly, frames are drawn faster.
Answer the question
In order to leave comments, you need to log in
I would use not setTimeout()
, namely requestAnimationFrame()
Inside, the elapsed time is known and you can understand which frame should now be displayed.
It is necessary to remember which frame is currently displayed: whether it needs to be redrawn, or whether it requestAnimationFrame()
worked twice during one frame and redrawing is not required.
So the animations will be rigidly tied to time. Even if a frame is skipped due to low performance, the overall speed of the animations is tied to time, and there will be no desync.
Instead of “braking”, slowing down, frames can be swallowed. But the speed of the character's movement in the animation will remain the same, albeit less smooth.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question