Reputation: 10896
Below is a snippet of JS/WebGL code that controls animation timing where
requestAnimFrame
is the usual shim. Works dandy under FireFox and Safari.
Under Chrome, the elapsedTime
becomes negative on frames 2 and onward.
Evidently (according to this article) webkitRequestAnimationFrame
does not
pass the currentTime
argument to the draw
callback!?! What is the proper, cross-browser method for computing the elapsed time!? THIS IS MADNESS!
var animationStartTime;
function draw(currentTime) {
requestAnimFrame(draw);
if (currentTime === undefined) {
currentTime = Date.now();
}
if (animationStartTime === undefined) {
animationStartTime = currentTime;
}
var elapsedTime = (currentTime - animationStartTime)/1000;
gl.clear(gl.COLOR_BUFFER_BIT);
drawScene(elapsedTime);
}
The actual WebGL program is here. Under FireFox and Safari you will see a single animation loop -- under Chrome you will see the animation go on forever (until I fix it).
Upvotes: 1
Views: 3278
Reputation: 23047
If I got you right - you want to measure time taken by rendering function? Then you should simply do this:
function draw() {
requestAnimFrame(draw);
var start = Date.now();
// perform your drawing
var elapsed = Date.now() - start;
}
But if you need FPS (Frames Per Second), then something like that will do:
var FPS = 0;
var ticks = 0;
var lastFPS = 0;
function draw() {
requestAnimFrame(draw);
// perform your drawing
var now = Date.now();
if (now - lastFPS >= 1000) {
lastFPS = now;
FPS = ticks;
ticks = 0;
}
ticks++;
}
Upvotes: 2