I'm curious about the best way to display cutscenes in canvas. When I say cutscene I mean something like a static image fading from one to the other. Would it be best to use a timeout for a certain amount of seconds then go to the next image? Alternatively, would it be better to somehow use the main loop and increment a counter? If anyone has a method they use, post an answer! :D
2 Answers
Don't use setInterval()
or so on for animating canvas. There is a requestAnimationFrame()
(MDN) function for this. It has better performance and more usefull in general.
Here is a good article about it: http://html5hub.com/request-animation-frame-for-better-performance
Use setTimeout()
instead of setInterval()
, because setTimeout()
will only run after a successful call, while setInterval()
would just stack many unhandled calls in case one of the calls takes more time to complete before another call is made. Combine it with requestAnimationFrame()
for even better performance plus not trying to render while the browser window is not even being shown.
This is what a standard JavaScript game loop usually looks like:
function getTime() {
return new Date().getTime();
}
function loop() {
var startTime = getTime();
screen.update();
var elapsedTime = getTime() - startTime;
var interval = FRAME_DURATION - elapsedTime;
setTimeout(onTimeout, interval);
function onTimeout() {
requestAnimationFrame(loop);
}
}
function main() {
loop();
}
main();
You have to issue the first call to loop()
from main()
(or whatever your main function is called) and then it will keep calling itself indefinitely. In the snippet above, screen.update()
is the method for your animation. And yes, you can have a ++tick
there to increment whatever property of your animation is required to make the transition.
window.setTimeout
. Instead, userequestAnimationFrame
. \$\endgroup\$