Chapter 2

image

HTML5 Development Strategies

In the previous chapter, we created a very basic HTML5 Pong game. The entire game was around 200 lines. We now want to make the game more interesting by adding sound and graphics. We also want to support mobile users. Because our time is precious to us, we don’t want to reinvent the wheel. We will use a game engine to do the low-level heavy lifting for us, but before doing that, we need to step back and look at a more formal approach to our development. This chapter presents some development and design theory. Our Pong game will receive its game engine in the next chapter.

2.1 Development Strategies

2.1.1 Progressive Enhancement and Graceful Degradation

Progressive Enhancement and Graceful Degradation are two strategies with the same goal of supporting as many devices as possible though they take opposite strategies.

Progressive Enhancement is the idea that you build your website to run on the weakest link possible. Perhaps you may not go as far back as IE6 (web developers like to keep their sanity), but turning off JavaScript on your browser as you build the site could be considered part of this strategy.

The core goal is to build your site using nothing but well-established standards and HTML tags focused on the meaning of the content rather than presentation (such as using <cite> to cite a reference versus <i> to just italicize it).

After your site is built this way, if a newer more capable browser comes along, you can add hooks to your solid foundation of code to give the user a better experience.

Graceful Degradation takes the opposite approach. It is the idea that you want to give your users the best experience possible. If they have a highly capable device, you want to give them the means to use it.

If a less-capable browser comes along, you want the code to “gracefully degrade.” For example, if the user does not have JavaScript enabled, instead of serving a broken page, you make sure your site was written in a way that still renders something workable to that user. Maybe not all features are available, but the core content is still accessible.

The pong game we have been developing does a poor job of graceful degradation. A browser without Canvas support will just get a blank or broken page. This is not acceptable in professional development. Many game engines (such as Crafty) support DOM-based drawing versus using pure Canvas. In the games you develop yourself, you should experiment with both and see which has the best performance on the browsers you want to support.

There are pros and cons to each strategy, and the proper approach could be the topic of a nice debate. The best strategy is dependent on the task. For example, a very content-oriented website (such as Wikipedia) benefits greatly with a progressive enhancement approach.

Video game development benefits from a graceful degradation approach. Audio is a big problem with HTML5 and mobile devices. The standard approach is to just turn sound off for mobile devices accessing via their internal browser. That doesn’t mean our app should be built without sound and then bolted on later. Eventually, mobile HTML5 audio will improve, the users will upgrade their phones, and our game will be ready for them.

There is a third, hybrid strategy to consider when developing a game or any app. It is called “mobile-focused development.” This strategy is also known as “Mobile First” and is often discussed when discussing the term responsive design. The idea is that mobile devices present a very unique challenge, and to give them a good experience, their needs must be addressed from Day 1. This strategy warrants an entire section. We intend to support mobile devices in this book.

2.1.2 Mobile-Focused Development

Developers love their mice and keyboards. It makes for fast and precise work. However, once your app leaves your workstation, chances are a mobile user will try to access it. If your app won’t run on their device, they will leave and possibly not come back. Depending on the stat agency and how the metric is calculated, mobile web access via tablets or phones now accounts for anywhere from 13% [36] to 27% [37] of all internet usage, and that number will continue to rise quickly as smartphones for the first time outsold “dumbphones” in 2013 [38].

If you don’t focus on mobile web users, your audience will shrink. Even users that are usually on a desktop browser very likely have a mobile internet device as their secondary. Naturally, they would prefer that your app worked on both.

There is actually a side benefit to such focus on mobile users: Their devices are weak. The current generation (mid-2013) high-end cell phones and tablets boast a power-conserving 1.4 GHz dual-core processor and usually 1 GB of RAM. The graphics processing unit is often embedded in the CPU. To find a current desktop with specifications that weak, you would have to reach for the low end of the all-in-one Black Friday deals. We as developers have been spoiled with multicore processors, lots of RAM, and good graphics processing being standard issue since 2008. Targeting mobile devices forces us to keep our apps fast and efficient. If your app can run tolerably on weak mobile devices at varying resolutions, it will probably run smoothly on a desktop.

Notice I didn’t mention our “big monitors” or “nice display resolution” in that paragraph about developers being spoiled by their workstations. This is because the monitor market has seen little innovation since 2006. This is because TV manufacturers tend to focus on just one market: HDTVs. That means computer monitor resolutions have been frozen at 1080p (1920 × 1080 pixels) for several years. Current tablets already exceed this resolution (iPad has 2048 × 1536) [32] while phones are just now meeting it (Samsung Galaxy S4 is 1920 × 1080 [39]).

An interesting situation has occurred with the fast improvement of mobile devices and stagnation of computer monitors: By the time you read this book, it is quite possible your 5-inch cell phone will be able to play your game at a higher resolution than your desktop. This is already true for many tablets.

2.2 Browser Wars?

Web developers are familiar with fighting all the different web browsers and keeping track of who is in the lead, a fight often called “The Browser Wars.” However, once you dig deeper and factor in mobile, you will see that this war is long over.

2.2.1 WebKit/Blink

On the desktop, there are several browsers with various shares of the market. They range from 10% to around 30% with Chrome as the market leader. There is no real market domination on the desktop, but it is possible Chrome may break away further and achieve a significant lead by the time you read this book. Chrome had a strong upswing in 2012–2013 gaining 8% [40]. See the chart in Figure 2.1. Note that Opera was left out since it only has 1% on the desktop.

Figure 2.1.

Figure showing Desktop browser share April 2012–April 2013.

Desktop browser share April 2012–April 2013.

However, as web developers, the name on the browser does not matter so much. It is the actual underlying engine, how the browser processes our HTML5, that we are concerned about. See the next chart in Figure 2.2 of market share with the common engines combined.

Figure 2.2.

Figure showing Desktop browser engine share April 2012–April 2013.

Desktop browser engine share April 2012–April 2013.

Webkit/Blink controls almost half of the desktop browser market. On April 3, 2013, Google forked the Webkit project and called it Blink [45], and as of version 28, Google is now deploying Blink as the rendering engine that powers Chrome [104]. The two will certainly diverge (e.g., Blink will not support any new vendor-specific CSS prefixes [44] (e.g., “-webkit-transform”), and Blink may abandon support for CSS Regions [66]), but for now, they are similar enough to be grouped together.

On mobile, the story on the surface looks about the same, with a handful of big players but no significant winner. See Figure 2.3.

Figure 2.3.

Figure showing Mobile browser market share April 2012–April 2013.

Mobile browser market share April 2012–April 2013.

Now, the same as before, the combined chart showing only the engines powering the browser. See Figure 2.4.

Figure 2.4.

Figure showing Mobile browser engine share April 2012–April 2013.

Mobile browser engine share April 2012–April 2013.

In the mobile landscape, there is essentially only one engine: WebKit/Blink. The two mobile market leaders (iOS and Android) both use WebKit/Blink as their base rendering engine, and the next closet leader, Opera, has announced a migration to Blink [41] (as it follows the Chromium project with Google).

This means the odd discrepancy when testing against multiple browsers may happen less often. However, iOS and Android web page behavior are not completely identical. Apple’s Safari uses Webkit’s built-in JavaScriptCore for their JavaScript engine, while Google’s Chromium project uses the V8 JavaScript engine for theirs [43]. Still, unlike desktop development, if you get it working on one, you are very close to getting it to work on the other.

Since Chrome is available on both Mac and Windows and uses the Webkit/Blink engine, and since it is also has best-in-class web development tools built in, it should be your browser of choice for mobile-focused development. If you are a fan of Firefox, it too has really good developer tools (launch using Ctrl+i, same as Chrome). Still, keep Chrome around because you need a WebKit-derived browser to support your testing. If you are a Windows user, you have little choice because Apple abandoned Safari for Windows as of Safari 6 [31]. Opera’s Blink-based browser was still in beta as of this writing.

2.2.2 Opera Mobile, Firefox Mobile, Windows Phone 8

All of the browsers in this subsection can be considered footnotes in development support. They are all very capable browsers, but they have not gained significant market share, and some of that can be attributed to Apple’s policy of not allowing any of these competing browsers into the iTunes store (clause 2.17 states browsers must use iOS Webkit [46]). The iTunes ban immediately eliminates 25% of the mobile browser competition. Essentially, we are only discussing alternative browsers available for Android when we discuss non-Webkit mobile browsers. This market is extremely small.

Opera was an early entry in mobile browsing. They developed an innovative feature with Opera Mini where they would perform server-side processing and send a low bandwidth result to the mobile device. This is exceptionally useful in cases where bandwidth is sparse or expensive (or both). Because of this unique feature, Opera Mini was allowed in iTunes. Opera was also one of the first mobile browsers that rendered pages well. These two features made Opera very dominant in mobile. Currently, Opera still holds around 15% market share with strong popularity on Blackberry devices. While Opera Mobile has excellent HTML5 support, Opera Mini has weak HTML5 support. As mentioned earlier, Opera Mobile is going to eventually follow the Chromium project and use Blink as the rendering engine. As of early 2014, there currently has been no announcement if Opera Mini will follow.

Firefox’s story is well-known. Firefox’s meteoric rise on the desktop forced Microsoft to restart development on IE 6 after letting it stagnate for five years [47]. Firefox Mobile has good HTML5 support on Android. Despite its good performance, Firefox may not experience strong growth on Android because Android devices already come with a good built-in browser.

Windows Phone 8 users have Internet Explorer 10 as their built-in browser [48]. It has good HTML5 support. Currently, mobile browsing with Internet Explorer is hovering at around 1%. Microsoft has made a big push for mobile with Windows 8 and their Surface tablet. We can wait and see if mobile IE can compete with Webkit/Blink dominance.

2.2.3 Browser Detection versus Feature Detection

The old way of handling different browsers is detecting which browser is being used. Depending on how the browser identifies itself (by looking at the User–Agent string), you would serve up a custom-made page. This worked fine in the days of Firefox versus Internet Explorer. However, there are now far more browsers on far more devices and these browsers are updated very rapidly. In 2010, Google adopted an aggressive six-week release cycle for Chrome [49]. In 2011, Mozilla adopted a similar six-week major release cycle for Firefox [27]. Once you factor in all the mobile devices and the fairly large fragmentation of Android, you can see that sending up a custom sheet for each combination of OS + Browser is unmaintainable.

2.2.4 The Old Wrong Way

See Listings 2.1 and 2.2 for various methods of browser detection. One uses conditional comments inside HTML. Conditional comments are only supported in IE. Therefore, you may see the jQuery version of detecting the browser agent. You should not do this. It is presented below so you can recognize it because the technique has been very prevalent. Note that even jQuery does not recommend using it and has removed this feature as of version 1.9. Browser detection should only be a technique of last resort. IE10 does not support conditional comments [53].

<! --  Do not do this !  -->

[if lt IE 7]> <link href =" ie_6_and_below . css "
 rel =" stylesheet " type =" text /css">
<! --[if IE 7] >
 <link rel=' stylesheet ' href =' ie7 .css ' type =' text /css '/ >
<![endif] -->
<! --[if IE 8] >
 <link rel=' stylesheet ' href =' ie8 .css ' type =' text /css '/ >
<![endif] -->

Listing 2.1. IE conditional comments.

// Do not do this !

if ($. browser . webkit) {
  alert (" This is Chrome or Safari !");
  // Do something just for WebKit
}
if ($. browser . mozilla) {
  alert (" this is Firefox !");
  // Do something just for Firefox
}
if ($. browser . msie) {
  alert (" this is IE!");
  // Do something just for IE
}

Listing 2.2. jQuery browser detect.

2.2.5 The Correct Way

The best way to determine if HTML5 features, such as Canvas, can be used on a browser is to simply ask or test if the browser supports it. If it does, then continue loading that branch of your app. For example, using the Modernizr library, a common test for HTML5 features is shown in Listing 2.3.

if(Modernizr . canvas && Modernizr . canvastext) {
  // Continue loading canvas
  if(Modernizr . audio) {
 // Which audio format to use ?
 if (Modernizr . audio .wav) {
  // Use wav
}
 if (Modernizr . audio .mp3) {
  // Use mp3
}
 if (Modernizr . audio .ogg) {
  // Use ogg
}
 // No audio format worked ? Perhaps use no audio .
 } else {
 // Audio not supported . Perhaps use the old <embed > method .
 }
} else {
// Degrade gracefully . Perhaps use DOM or check for Flash ?
}

Listing 2.3. Feature detect with Modernizr.

Modernizr has dozens of different browser checks delivered in a small package. It uses lots of tricks and even tries to work around known “false positives,” places where the browser says it supports a feature but further testing showed support is inadequate.

If you only care about a handful of these checks, the Modernizr website has a utility that can build a special version with just the checks you need. There is no configuration for Modernizr. Just include the JavaScript library, and it will generate a global “Modernizr” object that holds the results. Using feature detection with Modernizr allows anybody to use any browser they wish. If it happens to support Canvas, you can send them Canvas. If it doesn’t, you can try to degrade gracefully.

2.3 HTML5 Sound and Music

Audio has finally risen to prominence with HTML5. It now part of the core specification with the <audio> tag. With it, you can create an in-browser player with controls with a single line. All previous methods to put audio inside a page required embedding Flash, QuickTime, VLC, or whatever the client happened to have installed monitoring for an embedded object. Despite this new specification, sound and music right now still have some rough issues.

2.3.1 HTML5 Audio Formats

Despite audio becoming a first-class citizen, none of the browser manufacturers were able to agree on a standard format for it. Through these disagreements, two dominant formats arose: MP3 and Ogg Vorbis. To create a proper audio player that can play on all major browsers, you need to include both formats and then let the browser decide which one to use. In the next four figures, all the major browsers are shown attempting to play a 5s Wav, 10s MP3, and 15s Ogg. Take a look at images in Figures 2.5, 2.6, 2.7, 2.8, and 2.9.

Figure 2.5.

Figure showing HTML5 audio test IE.

HTML5 audio test IE.

Figure 2.6.

Figure showing HTML5 audio test Chrome.

HTML5 audio test Chrome.

Figure 2.7.

Figure showing HTML5 audio test Firefox 21 Windows.

HTML5 audio test Firefox 21 Windows.

Figure 2.8.

Figure showing HTML5 audio test Firefox 21 Mac.

HTML5 audio test Firefox 21 Mac.

Figure 2.9.

Figure showing HTML5 audio test Safari.

HTML5 audio test Safari.

The images are showing four browsers with three common formats, and results vary by platform and browser. IE only plays MP3. Chrome plays them all. Firefox 21 will only play MP3 for Windows. Safari does not play Wav. See Table 2.1 for a summary. Note that this chart may change by the time you read this book. While writing this book, Firefox 21 received MP3 support on Windows, and then Firefox 26 received it for the Mac.

Table 2.1.

HTML5 audio codec support.

Browser

Ogg Vorbis

MP3

WAV

Firefox 26

Yes

Yes

Yes

Chrome 32

Yes

Yes

Yes

Safari 7

Yes

Yes

Opera 19

Yes

Yes

IE 11

Yes

The only way to support all major browsers is to encode your files to MP3 plus Wav or Ogg. Since Ogg is significantly smaller than a standard Wav, that should be the preferred secondary format. Unlike MP3, Ogg is completely royalty free [50] [51], so it may eventually catch on to be a universal format for compressed audio.

Despite the annoying audio format war, previous problems of HTML5 are waning. With iOS 5 and below, you only had one audio channel to work with. Having one audio channel meant only one sound could play at a time. Audio hasn’t been this crippled since the 1980s. Though the quality of the sound was very limited, the original 8-bit Nintendo supported five audio channels [52].

Though the problem is now solved in hardware by adding more channels, the original software workaround was to have “sound sprites” similar to a normal sprite sheet (discussed next chapter). You would have one big file with all your sounds. When an event occurred, you’d jump the audio player to the correct sound location, play the sound, and then jump the audio player back. It was crude, but it worked. Fortunately, iOS6 and recent Android has better multiple audio channel support. By the time you read this book, you won’t need to worry about this, but keep that technique in mind if you want to support older browsers or old hardware (or simply enjoy game dev trivia).

To stay up to date on mobile and desktop browsers and what features of HTML5 are supported, you can visit http://html5test.com/. http://mobilehtml5.org is also a good resource for details specific to mobile.

2.4 Testing on Mobile Devices

Testing on desktop is pretty easy. Just open the HTML file, and see how it works. Tweak some code. Hit refresh. Mobile devices are not so simple because you are not directly editing your game on them (though you probably could, it would be very inefficient). Also, editing via the “File://” protocol does not usually work as it has lots of strict restrictions to prevent cross-site scripting and other security issues. In short, any serious website development needs an actual web server. This quick guide will teach you how to set up a local web server and connect your mobile device to it.

2.4.1 WAMP/XAMPP for Windows

WAMP (http://www.wampserver.com/) (and to some extent, XAMPP (http://www.apachefriends.org/)) is one of the easiest ways to get a development web server on your Windows machine. Two things to make sure of:

  1. Install it in a directory your user account has write access to, such as: c:UsersYourAccountNamewamp In the past, the normal procedure was to install the server in a folder off the root directory. This cannot be done as easily since Vista/Windows 7/Windows 8 has stricter permissions for apps. There will be file access issues. Also, some versions of these Windows-based servers have problems with spaces in directory names.
  2. If you have VMware installed (to test different operating systems), you may need to reconfigure SSL to run on a different port. One of VMware’s services likes to use 443, the default SSL port. For XAMPP, edit: xamppapacheconfextrahttpd-ssl.conf Search, find, and then change 443 to something else, like 4430. Figure 2.10 shows the SSL port being used by VMware and then starting on a different port.

Figure 2.10.

Figure showing Starting XAMPP with VMware warning.

Starting XAMPP with VMware warning.

WAMP does not enable SSL by default, so port 443 will not be opened. If you are using SSL on WAMP, the location and file is very similar. Look for it at: wampinapacheapache2.2.22conforiginalextrahttpd-ssl.conf

Start WAMP/XAMPP and then start Apache web server. For this book, there is no need for MySQL or any other standard service beyond Apache provided by the web server. Go to http://localhost/ to verify that your web server is running.

If you are looking for a personal recommendation on which development server to use, I have used XAMPP for eight years. However, the project has been lacking since user account controls (UACs) became normal in Windows Vista, 7, and 8. As of this writing, the official instructions describe how to turn off UAC [89]. This is undesirable for a professional environment. For new development environments, I recommend installing WAMP. For Mac, I use MAMP. Apple’s OS X Server’s web server works fine too. MAMP is simply easier to configure and remap the web root.

With the web server configured, you now need to know your IP address so you can view your web page on your mobile device (on the local desktop, you can just use “localhost” or “127.0.0.1” as the web address). Follow these steps:

  1. Windows Key + R, a command prompt appears.
  2. Type “cmd”. Press <enter>.
  3. Type “ipconfig”. Press <enter>.
  4. Look for your IPv4 address. You may have more than one. Your web server will try to bind to all addresses.

See Figure 2.11 for an example IP address output. You can see my IP address is 192.168.1.23. If I had another adapter connected (such as Ethernet), it would show as connected too, and I would have another IP address. You may want to give yourself a static IP address because you will be frequently visiting this address on your mobile devices. Note that you can give a single network adapter multiple IP addresses. This can be useful for testing separate networks with a single adapter (often called a “network bridge”). Also, if you have VMware installed, you may have additional virtual adapters with additional IP addresses being shown as connected. Find the IP addresses of the adapter that is connected to your local network.

Figure 2.11.

Figure showing Windows 7 ipconfig.

Windows 7 ipconfig.

Direct your mobile device’s browser to each entry in your list of IPV4 addresses. One of them should show the default welcome page. If none work, check that your mobile device is connected to Wi-Fi and not 3G/4G. If Wi-Fi is connected, try turning off Windows firewall (but don’t leave it off; set up a rule instead). Also, WAMP has two modes. Try clicking your WAMP task bar icon and select “Put Online.” One of WAMP’s modes is to just bind locally.

2.4.2 IIS for Windows

My personal recommendation for Windows web server development is WAMP presented earlier. I enjoy using the LAMP (Linux + Apache + MySQL + PHP/Python) stack, and WAMP quickly provides the “AMP” portion for Windows. However, Microsoft makes a capable web server available to Windows users. Setup requires a bit of effort. It involves navigating a lot of Control Panel options and advanced settings. The process is presented below. If you are happy with WAMP, then skip this section.

  1. Press WinKey and search and launch “Programs and Features”. Go to “Turn Windows Features on or off.”
  2. Check to turn on Internet Information Services. It will enable a lot of standard defaults.
  3. Important: Navigate to “World Wide Web Services” → “Application Development Features” and enable CGI. This is needed for PHP, which will be installed later.
  4. Click OK. When finished, go to http://localhost/ on your browser to see the IIS splash screen. With the web server working, you now need PHP (required for the Impact game engine).
  5. Download and install the PHP plugin for IIS at http://php.iis.net/.
  6. Navigate to the default IIS web root, which is “C:inetpubwwwroot.” Right-click on “wwwroot”. Select Properties.
  7. We are going to enable our account to have full control of this directory. Select Security tab. Select Advanced. Select Change Permissions. Select “Add....” Type in your username. Click “Check Names.” Click “OK.” Give yourself full control. Click OK to dismiss the pop-ups cluttering the screen.
  8. To make sure PHP is working, create a new file called “phpinfo.php” in your “wwwroot” directory. You should have write permissions to do this. Inside that file, put this:

    <?php
    phpinfo ();
    ?>
  9. To go http://localhost/phpinfo.php. You should now see the PHP information screen. This verifies IIS and PHP were installed correctly. The phpinfo() function can be used anywhere to check and verify PHP settings.
  10. If you want IIS to load “index.php” by default, you can launch the IIS manager. (Press WinKey and search for “IIS manage”). Navigate to “Default Site.” Look for “Default Document.”

2.4.3 MAMP for Mac

Before diving into MAMP, the absolute easiest way to get a web server running on a Mac is to use Python’s built-in HTTP server. Open Terminal (Go to Spotlight and search for “Terminal.” It also can be found in Applications/Utilities). Navigate to the directory containing your web files. Now, run this command:

python -m SimpleHTTPServer

You will then have a very simple HTTP server running for that location on port 8000. Go to http://127.0.0.1:8000 to view your pages. The Python server will work for the majority of the examples. The main exception is the Impact game engine. Impact requires PHP. Eventually, you will need a web server with PHP support.

Now, on to MAMP. MAMP is the easiest full development server for Mac users. To install MAMP, download it (http://www.mamp.info/), unzip it, and then right click to open it. Note that you have to use right click because in OS X Mountain Lion and above, the GateKeeper feature prevents unsigned installers from running normally. Install with default options. Navigate to your Applications folder, and then run MAMP. If it all goes well, you will see Figure 2.12 after starting the app.

Figure 2.12.

Figure showing MAMP window.

MAMP window.

We will not need MAMP Pro as PHP and Apache are sufficient for our purposes. Note: To ease development, you may want to set MAMP to use default HTTP port 80. Test the server by opening the start page. Now, you need to find the IP address of your Mac so you can go to it on you mobile device. To do this:

  1. Start Terminal (Go to Spotlight and search for “Terminal.” It also can be found in Applications/Utilities).
  2. Type “ifconfig.” Hit enter.
  3. Look for your “inet” device. You may have more than one. As before, my IP address is 192.168.1.23. I use the same IP address whether in Mac or Windows to make my development easier (Figure 2.13).

Figure 2.13.

Figure showing ifconfig Mac.

ifconfig Mac.

Navigate to that IP address on your mobile device. You should reach your Mac web server. With your IP addresses in hand, try each one on your mobile device to access the page. Make sure you are connected to Wi-Fi and not 3G/4G.

If you have access to a website with a web host, you also can upload and test your game in a private section of it. It’s a bit slower than using a local server, but it is a lot easier to set up and share. Take a look at FileZilla in the Tools Appendix. Some programming editors, such as Komodo Edit, are capable of directing remote files through FTP and SFTP. That can save you the upload step.

2.5 Optimizing the Page for Mobile

Apple has developed specific meta tags to help optimize pages for mobile devices. Fortunately, instead of reinventing the wheel, Android and Firefox have adopted these tags. Unfortunately, IE seems to want to use its own extensions. IE-specific meta tags can be safely combined with Apple-specific meta tags. Web browsers will skip meta tags they do not understand.

The various techniques to get your site (and our Pong game) to work for mobile users will be discussed in this section.

2.5.1 Mobile Meta Tags

Mobile meta tags use meta, name and content in their tagging. The boilerplate for mobile devices is as follows:

  <meta name =" viewport "
  content =" width = device -width , initial - scale =1.0 ">
  <meta name ="apple - mobile -web -app - capable " content ="yes">
  <meta name =" MobileOptimized "
  content =" width "> <! -- IE specific tag -->

These meta tags are telling the mobile device that the page has been optimized for mobile devices, and that it should set the viewport to the width of the device. There are many useful meta tags, such as setting the home screen button if the link is saved on an iPhone, but this is enough to get started. If you would like a shortcut to the proper ways of serving mobile and desktop users (and I am a big fan of shortcuts), HTML5 Boilerplate is an all-in-one starting template to build a modern HTML5-based website. It is discussed in the Tools Appendix.

2.6 Chrome Developer Tools

The Chrome Developer Tools are a very powerful set of tools for troubleshooting problems with your web page. To get to it, navigate to View → Tools → Developer Tools. You can also right click an element and “inspect” the element to launch the tools.

Despite the seemingly DOM-centric focus, there are a large number of useful features available to the HTML5 Canvas developer. Launch the Chrome Developer Tools and consider these tabs:

  1. Network is invaluable when troubleshooting timing and AJAX requests to the server. Beyond that, looking at this page is also a very quick way to determine if an asset is not getting loaded because of 404/Not Found errors.
  2. Profiles is the place to go for performance tuning. Often, 80% of the time is spent in just 20% of the code. Focusing on optimizing that 20% of the code will have the biggest payoffs. The 80/20 rule is often called the Pareto Principle [90]. It may not be obvious where the 20% is occurring. Start “Collect JavaScript CPU Profile.” Play the problem/slow area in the game. Stop the Profile, and then take a look. Chrome will show which functions are consuming the most CPU time.
  3. Console is incredibly useful. Drop “console.log()” all over the code to get debugging information. Chrome’s console is capable of accepting full JavaScript objects. The prompt also can evaluate JavaScript expressions.

Strive to become very familiar with Chrome’s Developer Tools. They are very useful.

2.7 Summary

This concludes Part I of the book. In the previous chapter, we built a proof-of-concept HTML5 game that can run on all modern (desktop) web browsers. The game was built entirely on standards-based technologies, so it will continue to be playable, and maintainable, for years to come. The game itself is rather dull. We have hit around 200 lines of code, and we still need to add sprites, sound, and mobile support. Before attempting those new features, we took a step back and used this chapter to discuss some higher level considerations, such as the needs of mobile users, the main browsers, and other development strategies.

In Part II of the book, we will stop writing everything from scratch and use game engines to help us. First, we will refactor and finish our Pong game using the conveniently lightweight Crafty game engine. Then we will build another lightweight game using the nongame-oriented EaselJS, and then a complex game will be made with the heavier engine Impact. Finally, we build our last game using the WebGL-based Turbulenz 3D game engine.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset