HTML and CSS Reference
In-Depth Information
Listing 15-4. Computing Frame Rate
var t =,
frame_count = 0, // increased on each Request Animation Frame (RAF)
//so we can compute avg_fps
avg_fps = 0; // FPS averaged over many frames
function tick() {
requestAnimationFrame( tick );
var n =,
raf_delta = n - t,
current_fps = 1000 / raf_delta;
t = n;
// you could compute average fps over many frames
avg_fps = (avg_fps * frame_count + current_fps) / ++frame_count;
// you could also add some code to display current_fps in a DOM element
myElement.innerHTML = current_fps + "FPS";
// read input, move things, render them
You could use the average frame rate to trigger resolution lowering (see the next section) but if you choose to do
so you should keep in mind the JavaScript engine compilation time discussed previously, since your frame rate will
suffer from it if your code hasn't been optimized.
Performance varies widely from device to device, so it might be a good idea to notify the user that his device is
not performing well when lowering resolution is not enough.
How to Lower Resolution
To lower the resolution and keep the game area the same size, you will downscale your viewport and canvas sizes,
and then upscale the canvas using CSS. As a result, you will compute fewer pixels and the browser will upscale them
almost for free. See Listing 15-5 for the code.
Listing 15-5. Lowering the Resolution
canvas.width = width * scaling;
canvas.height = height * scaling; = width + 'px';
gl.viewport( 0, 0, width * scaling, height * scaling );
Since you're use WebGL and a matrix to transform the vertices, you don't need to do anything else. If you
were to use canvas 2D, you would have to scale your sprites and their coordinates to draw them at the right place.
In Figure 15-4 , you can see that the graphic quality of our demo is severely degraded compared to Figure 15-3 .
Figure 15-4 exhibits the Bad Way™ of resolution lowering. Next, we'll discuss how to properly downscale your canvas
while maintaining graphic quality.
Search WWH ::

Custom Search