1
\$\begingroup\$

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

\$\endgroup\$
3
  • 1
    \$\begingroup\$ Do you mean 2D? If so, this is probably a dupe of: gamedev.stackexchange.com/questions/31694/… \$\endgroup\$
    – ashes999
    Commented Oct 31, 2013 at 20:54
  • 4
    \$\begingroup\$ "Best" is really subjective. If it works, it works. Code something up and see if you run into concrete problems. \$\endgroup\$ Commented Oct 31, 2013 at 21:17
  • \$\begingroup\$ Whatever you do, don't use window.setTimeout. Instead, use requestAnimationFrame. \$\endgroup\$ Commented Nov 2, 2013 at 15:01

2 Answers 2

0
\$\begingroup\$

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

\$\endgroup\$
0
\$\begingroup\$

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.

\$\endgroup\$