PROBLEM
I am trying to get an image on a canvas to move from left to right smoothly. It's not too bad on Chrome/Safari (still stutters a little), but there is noticeable stutter in Firefox on multiple machines (tried on Windows and Mac). I'm a bit stumped as to how to solve this.
WHAT I TRIED
I am using requestAnimationFrame instead of setTimeout. I am using clearRect instead of setting the canvas width, though I am clearing the entire canvas instead of the minimum bounding box as I wanted to test it in the worst case scenario. I did close extra tabs. I even disabled Firebug. I am using drawImage instead of the image data functions. Since I'm not doing anything else but clearRect and drawImage, I avoided using an offscreen canvas.
EXAMPLE 1: http://jsfiddle.net/QkvYs/
This one has a set framerate where it ensures that the position is correct regardless of how often the game loop runs. It displays the number of frames skipped. This example is closer to what I'm aiming for. Note that it looks choppy even when no frames are being skipped. I have also played around with the framerate with no success, though I'd like to aim for about 30 fps (var frameRate = 33;).
EXAMPLE 2: http://jsfiddle.net/R8sEV/
Here is a simple one where all it does is move the image. This stutters for me on multiple machines.
//loop
function loop() {
//request anim frame
requestAnimationFrame(loop);
//set canvas once able
if (!canvas) {
var temp = document.getElementById("testCanvas");
if (temp) {
canvas = temp;
ctx = canvas.getContext('2d');
}
}
//update and render if able
if (canvas) {
//increase x
x += 5;
//start from beginning
if (x > canvas.width) {
x = 0;
}
//clear
ctx.clearRect(0, 0, canvas.width, canvas.height);
//image
ctx.drawImage(image, x, 200);
}
}
//start
loop();
WHAT I LOOKED AT
I realize that this question has been asked before and I did look before asking. However, the answers given have unfortunately not helped.
https://gamedev.stackexchange.com/questions/37298/slow-firefox-javascript-canvas-performance
HTML5 Canvas Animation Has Occasional Jitter / Hesitation / Stutter
Canvas animation stutters in FireFox but is perfect in Chrome
Thanks for the help! I appreciate it.
For instance use time delta in your position calculations. This will ensure that object is moved by certain value in given time regardless of FPS and delay between frames.
Edited your fiddle: http://jsfiddle.net/R8sEV/2/
wrong approach:
x += 5
good approach:
x += speed * delta / 1000
where delta is time in [ms] which passed from last frame - and speed is measured in [pixels/second]