Skip to content Skip to sidebar Skip to footer

Canvas Animation Stutters In Firefox But Is Perfect In Chrome

I recently got about doing some HTML5/Canvas stuff and was going about my business quite happily, testing stuff in Chrome, until I decided to try what I have been working on in Fir

Solution 1:

The solution @HakanEnsari provided seems to work. I was curious about the reason and found that it's because his version of the code doesn't clear the entire canvas. It only clears the individual 10x10 Rects and leaves the rest of the canvas alone.

This goes into it a bit, and also has a lot of other useful canvas performance tips: http://www.html5rocks.com/en/tutorials/canvas/performance/#toc-render-diff

So you want this:

  function loop() {
    // get rid of this//canvas.width = canvas.width; requestAnimFrame(loop);

Just clear the individual rects

Rect.prototype.update = function () {  
    if (this.x < 0 || this.x > canvas.width) this.speedX = -this.speedX;
    if (this.y < 0 || this.y > canvas.height) this.speedY = -this.speedY;

    // clear just the rect
    context.clearRect(this.x, this.y, 10, 10);

    this.x += this.speedX;
    this.y += this.speedY;
  };

(tweaked fiddle: http://jsfiddle.net/shaunwest/B7z2d/1/)

Solution 2:

Apparently, clearing the canvas with canvas.width = canvas.width; caused the lag on Safari (I'm browsing with version 5.1.9).

I've never used that way of clearing the screen: instead, I use this one:

context.clearRect(0,0, canvas.width, canvas.height);

If you try it out, it shouldn't lag anymore. See jsfiddle.


This is the fastest way to clear the canvas: on the contrary, clearing each individual element requires you to:

  1. keep track of every element position
  2. perform a clearRect call for every element you want to redraw

and also wouldn't work for shapes other than a rectangle (as there is no clearSphere or clearPath method).

Solution 3:

Another reason of the stutters is that until FireFox24, the animations of FireFox was not fully synchronized to the refresh rate (VSYNC), especially if the refresh rate was not exactly 60Hz.

It has to do with the end of section 5 of W3C recommendation, http://www.w3.org/TR/animation-timing/ for the browsers to synchronize animations to the refresh rate. It now runs almost equally as smoothly in both Chrome and FireFox on Windows, since FireFox 24.

TestUFO lists all the supported browsers (that can sync requestAnimationFrame() to the refresh rate) at http://www.testufo.com/browser.html

Post a Comment for "Canvas Animation Stutters In Firefox But Is Perfect In Chrome"