How could I calculate the FPS of a canvas game application? I've seen some examples, but none of them use requestAnimationFrame, and im not sure how to apply their solutions there. This is my code:
(function(window, document, undefined){
var canvas = document.getElementById("mycanvas"),
context = canvas.getContext("2d"),
width = canvas.width,
height = canvas.height,
fps = 0,
game_running = true,
show_fps = true;
function showFPS(){
context.fillStyle = "Black";
context.font = "normal 16pt Arial";
context.fillText(fps + " fps", 10, 26);
}
function gameLoop(){
//Clear screen
context.clearRect(0, 0, width, height);
if (show_fps) showFPS();
if (game_running) requestAnimationFrame(gameLoop);
}
gameLoop();
}(this, this.document))
canvas{
border: 3px solid #fd3300;
}
<canvas id="mycanvas" width="300" height="150"></canvas>
By the way, is there any library I could add to surpervise performance?
Do not use new Date()
This API has several flaws and is only useful for getting the current date + time. Not for measuring timespans.
The Date-API uses the operating system's internal clock, which is constantly updated and synchronized with NTP time servers. This means, that the speed / frequency of this clock is sometimes faster and sometimes slower than the actual time - and therefore not useable for measuring durations and framerates.
If someone changes the system time (either manually or due to DST), you could at least see the problem if a single frame suddenly needed an hour. Or a negative time. But if the system clock ticks 20% faster to synchronize with world-time, it is practically impossible to detect.
Also, the Date-API is very imprecise - often much less than 1ms. This makes it especially useless for framerate measurements, where one 60Hz frame needs ~17ms.
Instead, use performance.now()
The Performance API has been specificly made for such use cases and can be used equivalently to new Date(). Just take one of the other answers and replace new Date() with performance.now(), and you are ready to go.
Sources:
Also unlike Date.now(), the values returned by Performance.now()
always increase at a constant rate, independent of the system clock
(which might be adjusted manually or skewed by software like NTP).
Otherwise, performance.timing.navigationStart + performance.now() will
be approximately equal to Date.now().
https://developer.mozilla.org/en-US/docs/Web/API/Performance/now
And for windows:
[The time service] adjusts the local clock rate to allow it to
converge toward the correct time.
If the time difference between the local clock and the [accurate time sample] is too large to correct by adjusting the local
clock rate,
the time service sets the local clock to the correct time.
https://technet.microsoft.com/en-us/library/cc773013(v=ws.10).aspx
Chrome has a built-in fps counter: https://developer.chrome.com/devtools/docs/rendering-settings
Just open the dev-console (F12), open the drawer (Esc), and add the "Rendering" tab.
Here, you can activate the FPS-Meter overlay to see the current framerate (incl. a nice graph), as well as GPU memory consumption.
Cross-browser solution:
You can get a similar overlay with the JavaScript library stat.js: https://github.com/mrdoob/stats.js/
It also provides a nice overlay for the framerate (incl. graph) and is very easy to use.
When comparing the results from stats.js and the chrome dev tools, both show the exact same measurements. So you can trust that library to actually do the correct thing.
You could keep track of the last time requestAnimFrame was called.
var lastCalledTime;
var fps;
function requestAnimFrame() {
if(!lastCalledTime) {
lastCalledTime = Date.now();
fps = 0;
return;
}
delta = (Date.now() - lastCalledTime)/1000;
lastCalledTime = Date.now();
fps = 1/delta;
}
http://jsfiddle.net/vZP3u/
Here's another solution:
var times = [];
var fps;
function refreshLoop() {
window.requestAnimationFrame(function() {
const now = performance.now();
while (times.length > 0 && times[0] <= now - 1000) {
times.shift();
}
times.push(now);
fps = times.length;
refreshLoop();
});
}
refreshLoop();
This improves on some of the others in the following ways:
performance.now() is used over Date.now() for increased precision (as covered in this answer)
FPS is measured over the last second so the number won't jump around so erratically, particularly for applications that have single long frames.
I wrote about this solution in more detail on my website.
I have a different approach, because if you calculate the the FPS you'll get this flickering when returning the number. I decided to count every Frame and return it once a second
window.countFPS = (function () {
var lastLoop = (new Date()).getMilliseconds();
var count = 1;
var fps = 0;
return function () {
var currentLoop = (new Date()).getMilliseconds();
if (lastLoop > currentLoop) {
fps = count;
count = 1;
} else {
count += 1;
}
lastLoop = currentLoop;
return fps;
};
}());
requestAnimationFrame(function () {
console.log(countFPS());
});
jsfiddle
I was missing an implementation that allows to customize the size of the sample for the averaged FPS value. Here is mine , it has the following features :
Accurate : performance.now() based
Stabilized : Returned FPS value is an averaged value ( fps.value | fps.tick() )
Configurable : FPS samples array size can be customized ( fps.samplesSize )
Efficient : Rotatory array for collecting samples (avoids array resizing)
const fps = {
sampleSize : 60,
value : 0,
_sample_ : [],
_index_ : 0,
_lastTick_: false,
tick : function(){
// if is first tick, just set tick timestamp and return
if( !this._lastTick_ ){
this._lastTick_ = performance.now();
return 0;
}
// calculate necessary values to obtain current tick FPS
let now = performance.now();
let delta = (now - this._lastTick_)/1000;
let fps = 1/delta;
// add to fps samples, current tick fps value
this._sample_[ this._index_ ] = Math.round(fps);
// iterate samples to obtain the average
let average = 0;
for(i=0; i<this._sample_.length; i++) average += this._sample_[ i ];
average = Math.round( average / this._sample_.length);
// set new FPS
this.value = average;
// store current timestamp
this._lastTick_ = now;
// increase sample index counter, and reset it
// to 0 if exceded maximum sampleSize limit
this._index_++;
if( this._index_ === this.sampleSize) this._index_ = 0;
return this.value;
}
}
// *******************
// test time...
// *******************
function loop(){
let fpsValue = fps.tick();
window.fps.innerHTML = fpsValue;
requestAnimationFrame( loop );
}
// set FPS calulation based in the last 120 loop cicles
fps.sampleSize = 120;
// start loop
loop()
<div id="fps">--</div>
Actually none of the answers were sufficient for me. Here is a better solution which:
Use's performance.now()
Calculates the actual average fps per second
Average per second and decimal places are configurable
Code:
// Options
const outputEl = document.getElementById('fps-output');
const decimalPlaces = 2;
const updateEachSecond = 1;
// Cache values
const decimalPlacesRatio = Math.pow(10, decimalPlaces);
let timeMeasurements = [];
// Final output
let fps = 0;
const tick = function() {
timeMeasurements.push(performance.now());
const msPassed = timeMeasurements[timeMeasurements.length - 1] - timeMeasurements[0];
if (msPassed >= updateEachSecond * 1000) {
fps = Math.round(timeMeasurements.length / msPassed * 1000 * decimalPlacesRatio) / decimalPlacesRatio;
timeMeasurements = [];
}
outputEl.innerText = fps;
requestAnimationFrame(() => {
tick();
});
}
tick();
JSFiddle
Just check the difference in time between the AFR-callbacks. AFR already passes the time as an argument to the callback. I updated your fiddle to show it: http://jsfiddle.net/WCKhH/1/
Just a proof of concept. Very simple code. All we do is set our frames per second and intervals between each frame. In the drawing function we deduct our last frame’s execution time from the current time to check whether the time elapsed since the last frame is more than our interval (which is based on the fps) or not. If the condition evaluates to true, we set the time for our current frame which is going to be the “last frame execution time” in the next drawing call.
var GameLoop = function(fn, fps){
var now;
var delta;
var interval;
var then = new Date().getTime();
var frames;
var oldtime = 0;
return (function loop(time){
requestAnimationFrame(loop);
interval = 1000 / (this.fps || fps || 60);
now = new Date().getTime();
delta = now - then;
if (delta > interval) {
// update time stuffs
then = now - (delta % interval);
// calculate the frames per second
frames = 1000 / (time - oldtime)
oldtime = time;
// call the fn
// and pass current fps to it
fn(frames);
}
}(0));
};
Usage:
var set;
document.onclick = function(){
set = true;
};
GameLoop(function(fps){
if(set) this.fps = 30;
console.log(fps);
}, 5);
http://jsfiddle.net/ARTsinn/rPAeN/
My fps calculation uses requestAnimationFrame() and the matching timestamp argument for its callback function.
See https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame and https://developer.mozilla.org/en-US/docs/Web/API/DOMHighResTimeStamp.
No need for new Date() or performance.now()!
The rest is inspired heavily by other answers in this thread, especially https://stackoverflow.com/a/48036361/4706651.
var fps = 1;
var times = [];
var fpsLoop = function (timestamp) {
while (times.length > 0 && times[0] <= timestamp - 1000) {
times.shift();
}
times.push(timestamp);
fps = times.length;
console.log(fps);
requestAnimationFrame(fpsLoop);
}
requestAnimationFrame(fpsLoop);
The best way that I use with performance.now()
Simple I passed TIME on gameLoop function and
calculate fps
fps = 1 / ( (performance.now() - LAST_FRAME_TIME) / 1000 );
(function(window, document, undefined){
var canvas = document.getElementById("mycanvas"),
context = canvas.getContext("2d"),
width = canvas.width,
height = canvas.height,
fps = 0,
game_running = true,
show_fps = true,
LAST_FRAME_TIME = 0;
function showFPS(){
context.fillStyle = "Black";
context.font = "normal 16pt Arial";
context.fillText(fps + " fps", 10, 26);
}
function gameLoop(TIME){
//Clear screen
context.clearRect(0, 0, width, height);
if (show_fps) showFPS();
fps = 1 / ((performance.now() - LAST_FRAME_TIME) / 1000);
LAST_FRAME_TIME = TIME /* remember the time of the rendered frame */
if (game_running) requestAnimationFrame(gameLoop);
}
gameLoop();
}(this, this.document))
canvas{
border: 3px solid #fd3300;
}
<canvas id="mycanvas" width="300" height="150"></canvas>
i had to create a function which sets on which fps should animation run, because i have a 240hz monitor and animations on my screen are much faster then on other screens, so that my end projects was always slower on other monitors
function setFPSandRunAnimation(fps, cb) {
let frameCount = 0;
let fpsInterval, startTime, now, then, elapsed;
runAnimating(fps);
function runAnimating(fps) {
fpsInterval = 1000 / fps;
then = Date.now();
startTime = then;
animate();
}
function animate(timestamp) {
requestAnimationFrame(animate);
now = Date.now();
elapsed = now - then;
if (elapsed > fpsInterval) {
then = now - (elapsed % fpsInterval);
const sinceStart = now - startTime;
const currentFps = Math.round(1000 / (sinceStart / ++frameCount) * 100) / 100;
const elapsedTime = Math.round(sinceStart / 1000 * 100) / 100;
cb(timestamp, currentFps, elapsedTime)
}
}
}
this is how to you use it
setFPSandRunAnimation(fpsSpeedYouWant, cbFunctionWhereYouGet timestamp, currentfps and elapsedTime).
inside of the cb function you can run any code you would run in animation function
Related
I want a constant frame rate using requestAnimationFrame. so I have this code:
let now, then, elapsed;
then = window.performance.now();
const fpsInterval = 1000 / 60;
function step(newtime) {
now = newtime;
elapsed = now - then;
if (elapsed > fpsInterval) {
then = now - (elapsed % fpsInterval);
// here constant frame rate is executed and available
}
reqAnimationFrame = window.requestAnimationFrame(step);
}
But the above code drops some frames and I need a more accurate solution.
Then I found this solution: https://stackoverflow.com/a/46346441/10715551
I think I need to use the code provided there to get a more accurate delta time and a more accurate constant frame rate:
var frameRate = 1000/60;
var lastFrame = 0;
var startTime;
function mainLoop(time){ // time in ms accurate to 1 micro second 1/1,000,000th second
var deltaTime = 0
if(startTime === undefined){
startTime = time;
}else{
const currentFrame = Math.round((time - startTime) / frameRate);
deltaTime = (currentFrame - lastFrame) * frameRate;
}
lastFrame = currentFrame;
requestAnimationFrame(mainLoop);
}
requestAnimationFrame(mainLoop);
The issue is I don't understand how I'm supposed to use this code in my code?
How can I create the most accurate constant frame rate possible?
Suppose I have a canvas that is 1200px. How do I get an object to move from the starting point (100px) to its endpoint (1000px) within a given time (eg. 10 seconds)? In such a way that it takes the object exactly 10 seconds to traverse from starting point to endpoint.
My code looks like this so far:
function setup()
{
createCanvas(img.width, img.height);
//Initialize x with the start value
x = startX;
}
function draw()
{
image(img, 0, 0);
x = min(endX, x);
x+=2;
//stop the object if it's near enough to endx and endy
if (abs(endX - x) < 30)
{
x = endX;
}
y = 114;
//stop the object if it goes off of the screen
x = min(x, 1200);
x = max(x, 0);
var spotlightSize = 114;
blendMode(BLEND);
background(10);
image(spotlight_image, x-spotlightSize/2, y-spotlightSize/2, spotlightSize, spotlightSize);
blendMode(DARKEST);
image(img, 0, 0);
}
If the frame rate was perfect and constant, you could simply divide the distance to travel by the amount of frames in the time that it takes. That result would be how far you need to travel in each frame. The frame rate is not perfect or constant, but we will write a program assuming a perfect frame rate because it will help us later.
What you need to do is:
Find how many frames will pass in the time you want to move - multiply the time to move by the frames per second
Find the displacement from the start to the end - subtract the start from the end
Divide the displacement by the amount of frames that will pass
Move that far each frame until you are close enough to the end
An example implementation: (you used only x-position but I used vectors as they will probably be useful to someone in the future)
new p5();
const fps = 60; // frames per second
const startPos = createVector(100, 50);
var position = startPos.copy();
const endPos = createVector(600, 450);
const stopAtDist = 30; // stop if it's this far from the end point in any direction
const distToTravel = p5.Vector.sub(endPos, startPos);
const moveDurationS = 10; // Move duration in seconds
const moveDurationFrames = moveDurationS / (1 / fps); // How many frames will it take to move the distance
const distToMovePerFrame = p5.Vector.div(distToTravel, moveDurationFrames); // How far to move each frame
var currentlyMoving = true;
function setup() {
createCanvas(800, 500);
frameRate(fps);
}
function draw() {
background(0);
// Draw the start pos
stroke('yellow');
strokeWeight(10);
point(startPos.x, startPos.y);
// Draw the end pos
stroke('green');
point(endPos.x, endPos.y);
// Draw the current position
stroke('red');
point(position.x, position.y);
// If it's currently moving, then move
if (currentlyMoving) {
position.add(distToMovePerFrame);
}
// If it is close enough to the end, then stop
if (abs(dist(position.x, position.y, endPos.x, endPos.y)) < stopAtDist) {
currentlyMoving = false;
}
}
The frame rate is not constant, though. Fortunately, p5 has a function that tells us how many milliseconds have passed in the last frame. So what we do is:
Find how many milliseconds pass in the time you want to move - multiply the seconds you want it to move for by 1000
Find out how far it will move per millisecond - divide the start/end displacement by the amount of milliseconds that will pass
Each frame, move the distance per millisecond multiplied by how many milliseconds have gone past in that frame.
Here's that translated into code:
new p5();
const fps = 60; // frames per second
const startPos = createVector(100, 50);
var position = startPos.copy();
const endPos = createVector(600, 450);
const stopAtDist = 30; // stop if it's this far from the end point in any direction
const distToTravel = p5.Vector.sub(endPos, startPos);
const moveDurationS = 10;
const moveDurationMs = moveDurationS * 1000;
const distToMovePerMs = p5.Vector.div(distToTravel, moveDurationMs);
var currentlyMoving = true;
function setup() {
createCanvas(800, 500);
frameRate(fps);
}
function draw() {
background(0);
// Draw the start pos
stroke('yellow');
strokeWeight(10);
point(startPos.x, startPos.y);
// Draw the end pos
stroke('green');
point(endPos.x, endPos.y);
// Draw the current position
stroke('red');
point(position.x, position.y);
// If it's currently moving, then move
if (currentlyMoving) {
var thisFrameMovement = p5.Vector.mult(distToMovePerMs, deltaTime);
position.add(thisFrameMovement);
}
// If it is close enough to the end, then stop
if (abs(dist(position.x, position.y, endPos.x, endPos.y)) < stopAtDist) {
currentlyMoving = false;
}
}
I tested the above code and it was pretty accurate - it averaged 0.75% off. I hope that this is what you're looking for in your answer!
According to several developers (link1, link2) the proper way to have a constant frame rate with requestAnimationFrame is to adjust the "last rendered" time within the game loop as follows:
function gameLoop() {
requestAnimationFrame(gameLoop);
now = Date.now();
delta = now - then;
if (delta > interval) {
then = now - (delta % interval); // This weird stuff
doGameUpdate(delta);
doGameRender();
}
}
Where interval is 1000/fps (i.e. 16.667ms).
The following line makes no sense to me:
then = now - (delta % interval);
Indeed if I try it I don't get smooth graphics at all but fast then slow depending on the CPU:
https://jsfiddle.net/6u82gpdn/
If I just let then = now (which makes sense) everything works smoothly:
https://jsfiddle.net/4v302mt3/
Which way is "correct"? Or what are the tradeoffs I am missing?
Delta time is bad animation.
It seems just about anyone will post a blog about the right way to do this and that, and be totally wrong.
Both articles are flawed as they do not understand how requestAnimationFrame is called and how it should be used in relation to frame rate and time.
When you use delta time to correct animation positions via requestAnimationFrame you have already presented the frame, it's too late to correct it.
requestAnimationFrame's callback function is passed an argument that holds the high precision time in ms (1/1000th) accurate to microseconds (1/1,000,000th) second. You should use that time not the Date objects time.
The callback is called as soon as possible after the last frame was presented to the display, there is no consistency in the interval between calls to the callback.
Methods that use delta time need to predict when the next frame is presented so that object can be render at the correct position for the upcoming frame. If your frame rendering load is high and variable, you can not predict at the start of frame, when the next frame will be presented.
The rendered frame is always presented during the vertical display refresh and is always on a 1/60th second time. The time between frames will always be integers multiples of 1/60th giving only frame rates of 1/60, 1/30, 1/20, 1/15 and so on
When you exit the callback function the rendered content is held in the backbuffer until the next vertical display refresh. Only then is it moved to display RAM.
The frame rate (vertical refresh) is tied to the device hardware and is perfect.
If you exit the callback late, so that the browser does not have time to move the canvas content to the display, the back buffer is held until the next vertical refresh. Your next frame will not be called until after the buffer has been presented.
Slow renders do not reduce frame rate, they cause frame rate oscillations between 60/30 frames per second. See example snippet using mouse button to add render load and see dropped frames.
Use the time supplied to the callback.
There is only one time value you should use and that is the time passed by the browser to the requestAnimationFrame callback function
eg
function mainLoop(time){ // time in ms accurate to 1 micro second 1/1,000,000th second
requestAnimationFrame(mainLoop);
}
requestAnimationFrame(mainLoop);
Post frame correction error.
Don't use delta time based animation unless you must. Just let the frames drop or you will introduce animation noise in the attempt to reduce it.
I call this post frame correction error (PFCE). You are attempting to correct a position in time for an upcoming and uncertain time, based on the past frame time, which may have been in error.
Each frame you are rendering will appear some time from now (hopefully in the next 1/60th second). If you base the position on the previouse rendered frame time and you dropped a frame and this frame is on time you will render the next frame ahead of time by one frame, and the same applies to the previous frame which would have been rendered a frame behind as a frame was skipped. Thus with only a frame dropped you render 2 frames out of time. A total of 3 bad frames rather than 1.
If you want better delta time, count frames via the following method.
var frameRate = 1000/60;
var lastFrame = 0;
var startTime;
function mainLoop(time){ // time in ms accurate to 1 micro second 1/1,000,000th second
var deltaTime = 0
if(startTime === undefined){
startTime = time;
}else{
const currentFrame = Math.round((time - startTime) / frameRate);
deltaTime = (currentFrame - lastFrame) * frameRate;
}
lastFrame = currentFrame;
requestAnimationFrame(mainLoop);
}
requestAnimationFrame(mainLoop);
This does not eliminate PFCE but is better than irregular interval time if you use delta time as timeNow - lastTime.
Frames are always presented at a constant rate, requestAnimationFrame will drop frames if it can not keep up, but it will never present mid frame. The frame rates will be at fixed intervals of 1/60, 1/30, 1/20, or 1/15 and so on. Using a delta time that does not match these rates will incorrectly position your animation.
A snapshot of animation request frames
This is a timeline of requestAnimationframe for a simple animation function. I have annotated the results to show when the callback is called. During this time the frame rate was constant at a perfect 60fps no frames where dropped.
Yet the times between callbacks is all over the place.
Frame render timing
The example shows frame timing. Running in SO sandbox is not the ideal solution and to get good results you should run this in a dedicated page.
What it shows (though hard to see for small pixels) is the various time error from ideal times.
Red is frame time error from the callback argument. It will be stable near 0ms from 1/60th second ideal frame time.
Yellow is the frame time error calculated using performance.now(). It varies about 2 ms in total with the occasional peek outside the range.
Cyan is the frame time error calculated using Date.now(). You can clearly see the aliasing due to the poor resolution of the date's ms accuracy
Green dots are the difference in time between the callback time argument and the time reported by performance.now() and on my systems is about 1-2ms out.
Magenta is the last frame's render time calculated using performance now. If you hold the mouse button you can add a load and see this value climb.
Green vertical lines indicate that a frame has been dropped / skipped
The dark blue and black background marks seconds.
The primary purpose of this demo is to show how frames are dropped as render load increase. Hold the mouse button down and the render load will start to increase.
When the frame time gets close to 16 ms you will start to see frames dropped. Until the render load reaches about 32ms you will get frames between 1/60 and 1/30, first more at 1/60th for every one at 1/30th.
This is very problematic if you use delta time and post frame correction as you will constantly be over and under correcting the animation position.
const ctx = canvas.getContext("2d");
canvas.width = 512;
canvas.height = 380;
const mouse = {x : 0, y : 0, button : false}
function mouseEvents(e){
mouse.x = e.pageX;
mouse.y = e.pageY;
mouse.button = e.type === "mousedown" ? true : e.type === "mouseup" ? false : mouse.button;
}
["down","up","move"].forEach(name => document.addEventListener("mouse"+name,mouseEvents));
var lastTime; // callback time
var lastPTime; // performance time
var lastDTime; // date time
var lastFrameRenderTime = 0; // Last frames render time
var renderLoadMs = 0; // When mouse button down this slowly adds a load to the render
var pTimeErrorTotal = 0;
var totalFrameTime = 0;
var totalFrameCount = 0;
var startTime;
var clearToY = 0;
const frameRate = 1000/60;
ctx.font = "14px arial";
var w = canvas.width;
var h = canvas.height;
var cw = w / 2; // center
var ch = h / 2;
var globalTime; // global to this
ctx.clearRect(0,0,w,h);
const graph = (()=>{
var posx = 0;
const legendW = 30;
const posy = canvas.height - 266;
const w = canvas.width - legendW;
const range = 6;
const gridAt = 1;
const subGridAt = 0.2;
const graph = ctx.getImageData(0,0,1,256);
const graph32 = new Uint32Array(graph.data.buffer);
const graphClearA = new Uint32Array(ctx.getImageData(0,0,1,256).data.buffer);
const graphClearB = new Uint32Array(ctx.getImageData(0,0,1,256).data.buffer);
const graphClearGrid = new Uint32Array(ctx.getImageData(0,0,1,256).data.buffer);
const graphFrameDropped = ctx.getImageData(0,0,1,256);
const graphFrameDropped32 = new Uint32Array(graphFrameDropped.data.buffer);
graphClearA.fill(0xFF000000);
graphClearB.fill(0xFF440000);
graphClearGrid.fill(0xFF888888);
graphFrameDropped32.fill(0xFF008800);
const gridYCol = 0xFF444444; // ms marks
const gridYColMaj = 0xFF888888; // 4 ms marks
const centerCol = 0xFF00AAAA;
ctx.save();
ctx.fillStyle = "black";
ctx.textAlign = "right";
ctx.textBaseline = "middle";
ctx.font = "10px arial";
for(var i = -range; i < range; i += subGridAt){
var p = (i / range) * 128 + 128 | 0;
i = Number(i.toFixed(1));
graphFrameDropped32[p] = graphClearB[p] = graphClearA[p] = graphClearGrid[p] = i === 0 ? centerCol : (i % gridAt === 0) ? gridYColMaj : gridYCol;
if(i % gridAt === 0){
ctx.fillText(i + "ms",legendW - 2, p + posy);
ctx.fillText(i + "ms",legendW - 2, p + posy);
}
}
ctx.restore();
var lastFrame;
return {
step(frame){
if(lastFrame === undefined){
lastFrame = frame;
}else{
while(frame - lastFrame > 1){
if(frame - lastFrame > w){ lastFrame = frame - w - 1 }
lastFrame ++;
ctx.putImageData(graphFrameDropped,legendW + (posx++) % w, posy);
}
lastFrame = frame;
ctx.putImageData(graph,legendW + (posx++) % w, posy);
ctx.fillStyle = "red";
ctx.fillRect(legendW + posx % w,posy,1,256);
if((frame / 60 | 0) % 2){
graph32.set(graphClearA)
}else{
graph32.set(graphClearB)
}
}
},
mark(ms,col){
const p = (ms / range) * 128 + 128 | 0;
graph32[p] = col;
graph32[p+1] = col;
graph32[p-1] = col;
}
}
})();
function loop(time){
var pTime = performance.now();
var dTime = Date.now();
var frameTime = 0;
var framePTime = 0;
var frameDTime = 0;
if(lastTime !== undefined){
frameTime = time - lastTime;
framePTime = pTime - lastPTime;
frameDTime = dTime - lastDTime;
graph.mark(frameRate - framePTime,0xFF00FFFF);
graph.mark(frameRate - frameDTime,0xFFFFFF00);
graph.mark(frameRate - frameTime,0xFF0000FF);
graph.mark(time-pTime,0xFF00FF00);
graph.mark(lastFrameRenderTime,0xFFFF00FF);
pTimeErrorTotal += Math.abs(frameTime - framePTime);
totalFrameTime += frameTime;
totalFrameCount ++;
}else{
startTime = time;
}
lastPTime = pTime;
lastDTime = dTime;
lastTime = globalTime = time;
var atFrame = Math.round((time -startTime) / frameRate);
ctx.setTransform(1,0,0,1,0,0); // reset transform
ctx.clearRect(0,0,w,clearToY);
ctx.fillStyle = "black";
var y = 0;
var step = 16;
ctx.fillText("Frame time : " + frameTime.toFixed(3)+"ms",10,y += step);
ctx.fillText("Rendered frames : " + totalFrameCount,10,y += step);
ctx.fillText("Mean frame time : " + (totalFrameTime / totalFrameCount).toFixed(3)+"ms",10,y += step);
ctx.fillText("Frames dropped : " + Math.round(((time -startTime)- (totalFrameCount * frameRate)) / frameRate),10,y += step);
ctx.fillText("RenderLoad : " + lastFrameRenderTime.toFixed(3)+"ms Hold mouse into increase",10,y += step);
clearToY = y;
graph.step(atFrame);
requestAnimationFrame(loop);
if(mouse.button ){
renderLoadMs += 0.1;
var pt = performance.now();
while(performance.now() - pt < renderLoadMs);
}else{
renderLoadMs = 0;
}
lastFrameRenderTime = performance.now() - pTime;
}
requestAnimationFrame(loop);
canvas { border : 2px solid black; }
body { font-family : arial; font-size : 12px;}
<canvas id="canvas"></canvas>
<ul>
<li><span style="color:red">Red</span> is frame time error from the callback argument.</li>
<li><span style="color:yellow">Yellow</span> is the frame time error calculated using performance.now().</li>
<li><span style="color:cyan">Cyan</span> is the frame time error calculated using Date.now().</li>
<li><span style="color:#0F0">Green</span> dots are the difference in time between the callback time argument and the time reported by performance.now()</li>
<li><span style="color:magenta">Magenta</span> is the last frame's render time calculated using performance.now().</li>
<li><span style="color:green">Green</span> vertical lines indicate that a frame has been dropped / skipped</li>
<li>The dark blue and black background marks seconds.</li>
</ul>
For me I never use delta time for animation, and I accept that some frames will be lost. But overall you get a smoother animation using a fixed interval than attempting to correct the time post render.
The best way to get smooth animation is to reduce the render time to under 16ms, if you can't get that then use deltat time not to set animation frame but to selectively drop frames and maintain a rate of 30 frames per second.
The point of a delta time is to keep the frame-rate stable by compensating for time taken by computations.
Think of this code:
var framerate = 1000 / 60;
var exampleOne = function () {
/* computation that takes 10 ms */
setTimeout(exampleOne, framerate);
}
var exampleTwo = function () {
setTimeout(exampleTwo, framerate);
/* computation that takes 30 ms */
}
In example one the function would calculate for 10 ms and then wait the frame-rate before painting the next frame. This will inevitably lead to a frame-rate lower than the expected.
In example two the function would start the timer for the next iteration immediately and then calculate for 30 ms. This will lead to the next frame being painted before the previous is done calculating, bottle necking your application.
With delta-time you get the best of both worlds:
var framerate = 1000 / 60;
var exampleThree = function () {
var delta = Date.now();
/* computation that takes 10 to 30 ms */
var deltaTime = Date.now() - delta;
if (deltaTime >= framerate) {
requestAnimationFrame(exampleThree);
}
else {
setTimeout(function () { requestAnimationFrame(exampleThree); }, framerate - deltaTime);
}
};
With delta-time, which represents the calculation time, we know how much time we have left before the next frame needs to be painting.
We don't have the sliding performance from example one and we don't have a bunch of frames trying to draw at the same time as in example two.
I've seen this kinda structure inside the update function in HTML5, Canvas games, with a "modifier" variable:
function update(modifier) {
obj.x += obj.speed * modifier
obj.y += obj.speed * modifier
}
function main() {
var thisLoop = new Date
var delta = thisLoop - lastLoop
update(delta / 1000)
render()
var lastLoop = new Date
}
var lastLoop = new Date
setInterval(main, 1)
Now I use myself this structure:
function update() {
obj.x += obj.speed
obj.y += obj.speed
render()
window.requestAnimationFrame(update)
}
What is the "modifier" supposed to do in the first structure?
And which one of them is the best to use, or is there maybe structure with both "modifier" and "requestAnimationFrame" too?
If you need your animation to be locked to time then you need a way to compensate for for example variable frame rates which of course then also have variable time between each frame.
A modifier could (as it's not shown how it is calculated) be used to fine-tune the speed/movement by compensating for this variation.
A couple of things though: don't use such as short time interval (1) as this could have an overall negative effect - you won't be able to update anything faster than the frame rate anyways so use nothing less than 16 ms.
Try to use requestAnimationFrame (rAF) instead as this is the only mechanism able to actually synchronize to the monitor update. rAF also passes a high-resolution timestamp which you can use for the compensator.
For example:
At 60 FPS you would expect a frame to last about 16.67ms.
So a modifier could be set as:
modifier = timeElapsed / 16.67;
If frame was able to run on time the value would be 1 in theory.
modifier = 16.67 / 16.67 = 1;
Now, if a frame iteration for some reason took more time, for example the double, you would get 2 as value for modifier.
modifier = 33.34 / 16.67 = 2;
How does this manifest in practical terms?
If you needed to move 100 pixels per frame then in the first situation when we were on time:
modifier = 16.67 / 16.67 = 1;
vx = 100 * modifier = 100; // # 1 frame = 100 pixels / frame
In the second case we spent two frames which means we needed it to move 200 pixels but since we didn't get that frame in between we need to use the modifier to compensate:
modifier = 33.34 / 16.67 = 2;
vx = 100 * modifier = 200; // # 2 frames = 100 pixels / frame
So here you see even if the frame rate was variant we moved what we expected to move anyways.
To calculate time elapsed simply use the rAF argument:
var oldTime = 0 // old time
frameTime = 1000 / 60; // frame time, based on 60 FPS, in ms
function loop(time) {
var timeElapsed = time - oldTime; // get difference
oldTime = time; // store current time as old time
var modifier = timeElapsed / frameTime; // get modifier based on FPS
...
requestAnimationFrame(loop);
}
Now, all that being said - modifier could also be just a value used to control speed... :-)
The newer version of requestAnimationFrame will return an elapsed time since the animation began.
You can use this elapsed time to determine where your animated objects should be redrawn.
For example, assume you have a ball object with an x property indicating it's x-coordinate.
If you want the ball to move 10 pixels right every 1000ms you can do this (untested!):
// set the starting x-coordinate of the ball
var ballStartingX=50;
ball.x=ballStartingX;
// get the time when the animation is started
var startingTime = performance.now();
// start the animation
requestAnimationFrame(update);
// update() is the animation loop function
function update(timestamp){
// request another frame
requestAnimationFrame(update);
// reposition the ball
// (timestamp-startTime) is the milliseconds elapsed
ball.x = ballStartingX + 10 * (timestamp-startTime)/1000;
}
I am trying to compare performance for 3d applications on mobile devices. I have a 3d solar system set up in webGL and im trying to record or at least display the FPS. So far this is what i Have:
in the body
<script language="javascript">
var x, message;
x = Time;
message = "fps is equal to ";
document.write (message); // prints the value of the message variable
document.write (x); //prints the value of x
</script>
and to get The Time Var in the draw function of canvas i have this
var Time = 0;
function drawScene() {
var startTime = new Date();
//draw scene here
var endTime = new Date();
Time = (endTime - startTime)
}
the output i get at the bottom of the canvas is "fps is equal to null"
any help would be great!
Displaying FPSs is pretty simple and has really nothing to do with WebGL other than it's common to want to know. Here's a small FPS display
const fpsElem = document.querySelector("#fps");
let then = 0;
function render(now) {
now *= 0.001; // convert to seconds
const deltaTime = now - then; // compute time since last frame
then = now; // remember time for next frame
const fps = 1 / deltaTime; // compute frames per second
fpsElem.textContent = fps.toFixed(1); // update fps display
requestAnimationFrame(render);
}
requestAnimationFrame(render);
<div>fps: <span id="fps"></span></div>
Use requestAnimationFrame for animation because that's what it's for. Browsers can sync to the screen refresh to give you buttery smooth animation. They can also stop processing if your page is not visible. setTimeout on the other hand is not designed for animation, will not be synchronised to the browser's page drawing.
You should probably not use Date.now() for computing FPS as Date.now() only returns milliseconds. Also using (new Date()).getTime() is especially bad since it's generating a new Date object every frame.
requestAnimationFrame already gets passed the time in microseconds since the page loaded so just use that.
It's also common to average the FPS across frames.
const fpsElem = document.querySelector("#fps");
const avgElem = document.querySelector("#avg");
const frameTimes = [];
let frameCursor = 0;
let numFrames = 0;
const maxFrames = 20;
let totalFPS = 0;
let then = 0;
function render(now) {
now *= 0.001; // convert to seconds
const deltaTime = now - then; // compute time since last frame
then = now; // remember time for next frame
const fps = 1 / deltaTime; // compute frames per second
fpsElem.textContent = fps.toFixed(1); // update fps display
// add the current fps and remove the oldest fps
totalFPS += fps - (frameTimes[frameCursor] || 0);
// record the newest fps
frameTimes[frameCursor++] = fps;
// needed so the first N frames, before we have maxFrames, is correct.
numFrames = Math.max(numFrames, frameCursor);
// wrap the cursor
frameCursor %= maxFrames;
const averageFPS = totalFPS / numFrames;
avgElem.textContent = averageFPS.toFixed(1); // update avg display
requestAnimationFrame(render);
}
requestAnimationFrame(render);
body { font-family: monospace; }
<div> fps: <span id="fps"></span></div>
<div>average fps: <span id="avg"></span></div>
I assume you are calling drawScene repeatedly but if you are setting x only once then it will not update every time drawScene is called. Also what you are storing in Time is elapsed time and not frames per second.
How about something like the below? The idea is to count the number of frames rendered and once one second has passed store that in the fps variable.
<script>
var elapsedTime = 0;
var frameCount = 0;
var lastTime = 0;
function drawScene() {
// draw scene here
var now = new Date().getTime();
frameCount++;
elapsedTime += (now - lastTime);
lastTime = now;
if(elapsedTime >= 1000) {
fps = frameCount;
frameCount = 0;
elapsedTime -= 1000;
document.getElementById('test').innerHTML = fps;
}
}
lastTime = new Date().getTime();
setInterval(drawScene,33);
</script>
<div id="test">
</div>
I created an object oriented version of Barış Uşaklı's answer.
It also tracks the average fps over the last minute.
Usage:
global Variable:
var fpsCounter;
Create the object somewhere when starting your program:
fpsCounter = new FpsCounter();
Call the update method in your draw() funktion & update the fps-displays:
function drawScene() {
fpsCounter.update();
document.getElementById('fpsDisplay').innerHTML = fpsCounter.getCountPerSecond();
document.getElementById('fpsMinuteDisplay').innerHTML = fpsCounter.getCountPerMinute();
// Code
}
Note: I only put the fps-display updates in the draw function for simplicity. With 60fps it gets set 60 times per second, even though once a second is enough.
FpsCounter Code:
function FpsCounter(){
this.count = 0;
this.fps = 0;
this.prevSecond;
this.minuteBuffer = new OverrideRingBuffer(60);
}
FpsCounter.prototype.update = function(){
if (!this.prevSecond) {
this.prevSecond = new Date().getTime();
this.count = 1;
}
else {
var currentTime = new Date().getTime();
var difference = currentTime - this.prevSecond;
if (difference > 1000) {
this.prevSecond = currentTime;
this.fps = this.count;
this.minuteBuffer.push(this.count);
this.count = 0;
}
else{
this.count++;
}
}
};
FpsCounter.prototype.getCountPerMinute = function(){
return this.minuteBuffer.getAverage();
};
FpsCounter.prototype.getCountPerSecond = function(){
return this.fps;
};
OverrideBuffer Code:
function OverrideRingBuffer(size){
this.size = size;
this.head = 0;
this.buffer = new Array();
};
OverrideRingBuffer.prototype.push = function(value){
if(this.head >= this.size) this.head -= this.size;
this.buffer[this.head] = value;
this.head++;
};
OverrideRingBuffer.prototype.getAverage = function(){
if(this.buffer.length === 0) return 0;
var sum = 0;
for(var i = 0; i < this.buffer.length; i++){
sum += this.buffer[i];
}
return (sum / this.buffer.length).toFixed(1);
};
Since none of the other answers addressed the "in WebGL" part of the question, I'll add the following important details when measuring FPS in WebGL correctly.
window.console.time('custom-timer-id'); // start timer
/* webgl draw call here */ // e.g., gl.drawElements();
gl.finish(); // ensure the GPU is ready
window.console.timeEnd('custom-timer-id'); // end timer
For simplicity I used the console timer. I'm trying to make the point to always use WebGLRenderingContext.finish() to ensure the correct time is measured as all WebGL calls to the GPU are asynchronous!
Using a rotating array can do better.
with dom element:
<div id="fps">
the following script do the trick:
var fpsLastTick = new Date().getTime();
var fpsTri = [15, 15, 15]; // aims for 60fps
function animate() {
// your rendering logic blahh blahh.....
// update fps at last
var now = new Date().getTime();
var frameTime = (now - fpsLastTick);
fpsTri.shift(); // drop one
fpsTri.push(frameTime); // append one
fpsLastTick = now;
fps = Math.floor(3000 / (fpsTri[0] + fpsTri[1] + fpsTri[2])); // mean of 3
var fpsElement = document.getElementById('fps')
if (fpsElement) {
fpsElement.innerHTML = fps;
}
}