Is there a solution for HTML5 canvas animation stu

2019-02-20 06:54发布

问题:

I am working on a HTML5 canvas animation (to be more precisely a photo slideshow). So far all my slideshows are in flash because last time (March 2010) I looked ihe framerate for Flash was much higher 3x - 4x compared to html5 canvas. Today it is said that current browsers catched up with flash but all the html5 canvas samples I have found so far stutter in current Firefox and Chrome browsers.

IN the sample setInterval is set to 15ms which should give alt least 60 fps. But at on my laptop the animation stutters a lot: http://demo.webdevhub.net/canvas/simple/

Are there workarounds for at least the up to date browsers or do I have to wait for another year?

Best Regards, Mark

回答1:

It seems to be fine in FF5 on Windows 7. Also seems smooth on IE9.

I think part of the problem may be that your interval is too small. On slower devices, it may go 66 frames per second when it can but then drop down to far fewer, then go back up to 66fps, giving a stutter effect.

By giving a very fast interval, you're effectively telling it to run as fast as it can, and it apparently needs to catch its breath. Maybe not though, maybe there's something else at work.

Try using an interval of 50ms and see what happens.

And for kicks, instead of using setInterval, see if using requestAnimFrame helps your problem at all. It may have the same problems as the fast interval though.

// shim for requestAnimFrame with setTimeout fallback
    window.requestAnimFrame = (function(){
      return  window.requestAnimationFrame       || 
              window.webkitRequestAnimationFrame || 
              window.mozRequestAnimationFrame    || 
              window.oRequestAnimationFrame      || 
              window.msRequestAnimationFrame     || 
              function(/* function */ callback, /* DOMElement */ element){
                window.setTimeout(callback, 1000 / 60);
              };
    })();


    // usage: 
    // instead of setInterval(render, 16) ....

    (function animloop(){
      render();
      requestAnimFrame(animloop, element);
    })();


回答2:

I'm currently working on a HTML5 BomberMan-clone and at first I tried to make some best-implementations of JavaScript gameLoops (google), but in the end I ended with a simple setTimeout(...) gameLoop :).

And as it seems it's working quite nicely and smooth. I have still lots of work to do, but you can see the current-dev-version (setTimeout is set for 30 FPS - but if I set it to 60 FPS - no problems at all) here:

(and thanks Simon for your drawing-optimizations comments all the time here on StackOverflow)

http://sabiland.net/Testing/BomberMan_Dev/BomberMan.aspx