|

HTML5 Games: Fixing Our Demo

In my HTML5 Games: Optimizing Your Game Loop I created a demo app in order to show you some techniques for optimizing a game loop. In that post we covered the demo creation, along with some browser tools, and narrowed down the areas we need to target for optimizing the loop.

So, let’s now see what we can do about the main areas in which our unoptimized demo is falling short and how to solve the problems. There is nothing too off-the-wall here — just some relatively simple techniques that improve performance at the expense of a heavier memory footprint. Again, here you can view the demo in motion: http://moot-point.com/demos/loop/loop-unoptimized.html–go back to the other post for the code involved.

This is not intended to be an exhaustive list of all possible optimizations you could make, but instead a good example of what be be quickly gleaned using the browser profiling tools.

1. Cache the results of DOM function calls

Notice how many DOM functions are contained within the enderShipAt() function! Any child functions in here are getting run 5000 times per cycle of the game loop.

A good rule of thumb is to consider DOM functions to be the slowest of the slow. Any functions that actually need to touch the DOM hierarchy in any way should be considered with the same care as a floor of hot coals.

In this case, getElementById() is our biggest culprit, so we would ideally call getElementById() only once during the initialization, and cache the results for later use.

2. Buffer the results of canvas operations that can be re-used

The other contributors are native canvas API functions — drawImage, rotate, translate, save, and restore. Normally there is no way of avoiding these, but since these are all being called 5,000 times each, they are quite the doozy in terms of our poor CPU.

Again, we can minimize their use by doing these canvas transformations only once per game loop. The strategy in this case would be to create another canvas object to be used as a buffer, draw the transformed image to this buffer, and then clone that buffer 5,000 times.

This enables us to call rotate, translate, save, and restore only once, rather than 5,000 times.

3. Minimize use of trig functions

We are calling Math.sin and Math.cos 5,000 times per loop. This could be made more efficient by implementing a lookup table that pre-computes all possible values up-front during our initialization, rather than doing all of this trig on-the-fly.

4. Minimize function calls

Since an overhead is associated with each function call, it is in our best interest to remove as many user-defined functions as possible. Ideally we can combine all of our statements into a single, concise function. Of course, doing so can come at the cost of readability, maintainability, and profilability (to coin a term), so this is best done as late in the development cycle as possible.

The Optimized Loop

Alright, let’s rewrite this thing!

After I made adjustments to the demo code according to the suggested optimizations above, I ran the demo once more. You can see it here: http://moot-point.com/demos/loop/loop-optimized.html.

This time, we have managed to hit a much heartier 57 fps.

Conducting another 30-second profiling session, we can see more evidence of the improvements:

Here is the complete optimized code:

        var canvas;
        var context;
        var width;
        var height;
        var shipImage;
        var canvasBuffer;
        var contextBuffer;
        var angle = 0;
        var lookupTable;

        //called once upon load of page
        function onLoad() {

            // cache dom elements
            canvas = document.getElementById('my_canvas');
            context = canvas.getContext('2d');
            width = canvas.width;
            height = canvas.height;
            shipImage = document.getElementById('ship');

            // create canvas buffer
            canvasBuffer = document.createElement('canvas');
            contextBuffer = canvasBuffer.getContext('2d');
            canvasBuffer.width = 100;
            canvasBuffer.height = 100;
            contextBuffer.translate(50, 50); // so we can rotate about the center point

            // create lookup table for trig functions
            angleIncrement = Math.PI / 12;
            lookupTable = [];
            for (var i = 0; i < 5000; i++) {
                lookupTable[i] = {
                    x: Math.cos(i) * width - 150,
                    y: Math.sin(i) * height - 150
                };
            }

            // kick off the loop
            window.setInterval(update, 16);
        }

        // this is called using a 16 ms interval
        function update() {

            // draw transformed ship image to a canvas buffer
            contextBuffer.clearRect(0, 0, 100, 100);
            contextBuffer.rotate(angleIncrement);
            contextBuffer.drawImage(shipImage, 0, 0, 50, 50);

            // draw 5,000 ships
            for (var i = 0; i < 5000; i++) {
                var lookup = lookupTable[i];
                context.drawImage(canvasBuffer, lookup.x, lookup.y);
            }
        }

Now you have some powerful profiling tools in your arsenal to optimize your game loop!

Safari Books Online has the content you need

Check out these HTML5 books available from Safari Books Online that will help you develop HTML5 games:

You’ll learn how to build interactive multimedia applications with HTML5 Canvas, using this new element to draw, animate, compose images, and more. You’ll also learn the best way to use existing JavaScript libraries, as well as how to incorporate related aspects such as audio and video.
Foundation HTML5 Canvas: For Games and Entertainment teaches you how to make exciting interactive games and applications using HTML5 canvas. Canvas lets you produce graphics, animations, and applications using the HTML5 and JavaScript web standards. It allows you to draw directly within the browser without the need for third-party plugins like Adobe Flash, and so canvas works perfectly across desktop and mobile devices, like the iPhone and Android.
HTML5 Games Development by Example will show you how to use latest HTML5 and CSS3 web standards to build card games, drawing games, physics games and even multiplayer games over the network. With the book you will build 6 example games with clear step-by-step tutorials.
HTML5 Canvas Cookbook begins by covering the basics of the HTML5 Canvas API and then provides techniques for handling features not directly supported by the API such as animations and canvas interactivity. It winds up by providing detailed templates for a few of the most common HTML5 canvas application.
Core HTML5 Canvas: Graphics, Animation, and Game Development presents a code-fueled, no-nonsense deep dive into that API, covering everything you need to know to implement rich and consistent web applications that run on a wide variety of operating systems and devices.
If you’re a web developer looking to use this new version of HTML, you might be wondering how much has really changed. Head First HTML5 Programming introduces the key features — including improved text elements, audio and video tags, geolocation, and the Canvas drawing surface — and uses concrete examples and exercises to apply and reinforce these concepts.

About this author

Kevin Moot has had an interest in computer graphics since creating games as a wee lad on his Apple IIe – complete with its vast array of six colors and a mind boggling 280×192 resolution. Kevin has worked with HTML5’s canvas technology for several cutting-edge websites and counts HTML/CSS, JavaScript and .NET among his specialties. He currently works at The Nerdery as an interactive software developer.

About Safari Books Online

Safari Books Online is an online learning library that provides access to thousands of technical, engineering, business, and digital media books and training videos. Get the latest information on topics like Windows 8, Android Development, iOS Development, Cloud Computing, HTML5, and so much more – sometimes even before the book is published or on bookshelves. Learn something new today with a free subscription to Safari Books Online.
|

Comments are closed.