Maintaining a consistent frame rate with HTML5
Posted: Tue Nov 29, 2011 1:42 pm
I've been having trouble trying to maintain a consistent frame rate with HTML5 (I'm using Firefox right now, when I get back home I'll be using Chrome). In order to get my frame updates
I've been using javascript's setInterval function, and to combat the inconsistencies of the times my function is called I've been using a delta value. This is my first time using a delta value,
so I probably missed something, any help would be appreciated.
The script:
EDIT: I should have also mentioned that the main reason I'm asking this question is because the above code randomly decides to jump about 70 pixels, along with being jittery
I've been using javascript's setInterval function, and to combat the inconsistencies of the times my function is called I've been using a delta value. This is my first time using a delta value,
so I probably missed something, any help would be appreciated.
The script:
Code: Select all
var canvas = document.getElementById("testCanvas");
var g = canvas.getContext("2d");
setInterval(update, (1000/60));
var x = 50;
var xvel = 2;
var lastTime = new Date();
var oneFrame = (1000/60); //we want 60 fps, so divide one second by 60
var extra = "";
function update() {
var currTime = new Date();
var delta = currTime.getMilliseconds()-lastTime.getMilliseconds();
var incrementAmount = ((xvel/oneFrame)*Math.abs(delta));
x += incrementAmount;
if(x > canvas.width-25) {
xvel = -xvel;
x = canvas.width-25;
} else if(x < 0) {
xvel = -xvel;
x = 0;
}
paint();
lastTime = new Date();
}
function paint() {
g.clearRect(0, 0, canvas.width, canvas.height);
g.strokeStyle = "#000000";
g.strokeRect(0, 0, canvas.width, canvas.height);
//actually draw our square
g.fillStyle = "#0000FF";
g.fillRect(x, 25.5, 25, 25);
g.fillText("x: "+x+", extra: "+extra, 5, canvas.height-25);
}