The FrameRateCounter Object Prototype
Arcade games such as Asteroids and Geo Blaster Basic rely on fast processing and screen updates to ensure that all game-object rendering and game-play logic are delivered to the player at a reliable rate. One way to tell whether your game is performing up to par is to employ the use of a frame rate per second (FPS) counter. Below is a simple one that can be reused in any game you create on the canvas:
//*** FrameRateCounter object prototype
function
FrameRateCounter
()
{
this
.
lastFrameCount
=
0
;
var
dateTemp
=
new
Date
();
this
.
frameLast
=
dateTemp
.
getTime
();
delete
dateTemp
;
this
.
frameCtr
=
0
;
}
FrameRateCounter
.
prototype
.
countFrames
=
function
()
{
var
dateTemp
=
new
Date
();
this
.
frameCtr
++
;
if
(
dateTemp
.
getTime
()
>=
this
.
frameLast
+
1000
)
{
ConsoleLog
.
log
(
"frame event"
);
this
.
lastFrameCount
=
this
.
frameCtr
;
this
.
frameLast
=
dateTemp
.
getTime
();
this
.
frameCtr
=
0
;
}
delete
dateTemp
;
}
Our game will create an instance of this object and call the
countFrames()
function on each frame
tick in our update()
function. We
will write out the current frame rate in our render()
function.
Example 8-11 shows these
functions by adding code to Example 8-10. Make sure you add
the definition of the FrameRateCounter
prototype object to the code
in Example 8-10 under the
canvasApp()
function but before the
final <script>
tag.
Alternatively, you can place it in its own <script\>
tags or in a separate .js file and
set the URL as the src=
value of
a <script>
tag. For simplicity’s ...
Get HTML5 Canvas, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.