Tag Archives: HTML5

Adding require.js to HTML5 boilerplate build

HTML5 boilerplate has a really nice build script. It get’s your website in tip top and minified shape in no time. However what happens when you want to use require.js on a big project and don’t need the scripts.js file that is provided? In a few steps we can get your website in tip top shape with require.js as well!

Getting started

For the sake of simplicity we will assume you already have h5bp in your project. Now that is settled we can get started.

First off we are going to need a way to differentiate our require.js stuff from the rest of our site. H5bp already has a good mechanism for doing this with external libraries via the libs & mylibs folders. From what I can gather libs & mylibs are where you stick generic libraries that the project may need. (jQuery, Backbone, etc)

For our require.js code we are going to create a separate folder called “app”. This way we can isolate those files from the h5bp build script. By default h5bp will copy & minify everything from the js folder when executed. This not what we want since we need to trace the require.js files for dependancies first. Your default js folder structure should be like below.

Cleaning up after scripts.js

Since we are no longer using the default scripts.js file we will need to modify the build script accordingly. Again, by default h5bp will try to run the -js.scripts.concat target when building. This will fail the checksum since we don’t have a scripts.js file. To remedy this problem remove any references to the ‘-js.scripts.concat’ target in the build targets. Doesn’t make sense? See below.

And… So close. One last modification is needed. When building, the ‘-usemin’ target is ran before any other minification/concat targets. Currently, it has a dependency on the ‘-js.scripts.contact’ target. We will need to get rid of this. However, this would be a good spot to trace our require module dependancies since it will run before any copying, minifying, etc. Go ahead and change the depends attribute to “-r.js,-css”. In the next section we will create the -r.js target.

Creating the -r.js target

<!-- Require.js target, run separately -->
<target name="-r.js" description="Concatenates JS files using require.js dependencies">
    <java classname="org.mozilla.javascript.tools.shell.Main">
        <classpath>
            <pathelement location="./${dir.build.tools}/${tool.rhino}" />
        </classpath>
        <arg value="tools/${tool.require}" />
        <arg value="-o" />
        <arg value="${require.build}" />
    </java>
    <echo message="optimized ${require.build}">
</target>
view raw r.js.xml This Gist is brought to you using Simple Gist Embed.

Let’s break this down a bit. First, it invokes Java. Next, it adds rhino to the java classpath. Finally, it sets three arguments.

If you notice there are three variables within the target. tool.rhino, tool.require, and require.build. The convention when defining variables within h5bp is to define them in the project.properties file. These variables override the default.properties file with your project specific variables. This is a good thing since if you update html5 boilerplate it won’t break your already defined variables with a later build. But what are these variables? The are simply string variables defined in our project.properties file.

${tool.rhino}

tool.rhino is defined in many places within the h5bp build.xml file. It is the string variable representing the rhino jar file.

${tool.require}

tool.require is a custom variable which represents the path to the r.js file that comes with the require.js optimizer. r.js will trace your javascript files written in require.js AMD format for dependencies, then concatenate them together and finally minify them with uglify. You will need to download this file and drop it in the tools directory within the build folder.

${require.build}

require.build is another custom variable that links to our require.js build file. As described above r.js will preform a build on your javascript files. However, it needs to know how and where to build from. This is where a custom build file comes in. Require.js can build your site based on this custom build file which is represented in json format. In the example below we have set the require.build variable to point to a file name app.build.js. This file contains the instructions on how to build our require.js modules.

app.build.js

To get the full rundown of what can be done in a require build file visit http://requirejs.org/docs/optimization.html

A simple example of a build file is below. In this example we define our base url in the app folder, then we define the name of our module we want to traverse and finally, the location where we want to publish out the generated file(s).

Note: we are publishing out to the intermediate folder created by the h5bp build script.

Putting it all together

Now that we have defined the variables above the -r.js target should make a bit more sense. Again, all it is doing is reading our require build file and tracing the module dependancies. It does this using the rhino shell to execute the r.js optimizer script that comes with require.js.

${dir.js.app}

Almost done. I promise! We will need to exclude our app folder from any processes that might get run by h5bp internally. We can do this in three steps.

  • Create a custom variable to our app path in project.properties.
  • Add ${dir.js.app} to the list of files/folders to ignore in project.properties.
  • Add an exclude statement to the -js.all.minify target. This will prevent h5bp from minifiying and copying the app folder. See below.

Conclusion

Ok, maybe that was more complicated that I thought! Anywhooo, if you had trouble following along I have attached the modified build folder below. Hopefully this helps development teams that are looking to incorporate require.js into their current build processes. Please feel free to post suggestions or enhancements.

build.zip

A tale of two app stores

After finishing my first PhoneGap application (Spelling Bees) and publishing to the Android Market and the Apple app store, I thought it would be a good time to reflect on the whole process. The intention is to help folks getting started building HTML5 games with PhoneGap and some of the issues that can arise when developing for multiple platforms.

App Links

Apple App Store
Android Market

Technologies Used

Before diving into the specific app stores/markets it would be beneficial to talk a bit about the strategies used to develop Spelling Bees.

PhoneGap

For those of you not familiar with PhoneGap, in a nutshell it is a wrapper that allows you to write your game with HTML5, CSS3, and JavaScript. The files can then be published as a native application on iOS, Android, Windows Phone, etc. PhoneGap also has hooks into hardware features such as camera, accelerometer, lifecycle events, etc.

Crafty.js

Crafty.js is a JavaScript framework that features collision detection, eventing, scene management, and an entity component system. Having tried out a few js game frameworks crafty was by far the easiest to get up and running in. Spelling Bees had multiple screens to navigate through. There is the main screen, levels, help, and actual game. Crafty helped organize each into a Crafty.scene() which could then be called later. Also, crafty made it super simple to add collision detection and simulated gravity with the component system.

A sample crafty scene for the game over screen.

jQuery tmpl

jQuery templating was invaluable on this project. Once I had my Crafty.scene() defined I wanted to pull in a template of what each screen should look like. Below is an example of the high score screen.

In the example above I could dynamically pass in the high scores to the template and render once the game ended.

Lawnchair

When playing spelling bees levels are locked until you pass the previous one. The game also saves high scores and state information in case the player gets a phone call and needs to resume the game. All this data is being stored in a websql database on the device. Lawnchair is a simple library that lets you store and retrieve data in JSON format. It abstracts out all the websql stuff which makes it dead simple to retrieve and store game data.

CSS3 Transforms

Transforms are your new best friend when animating with mobile devices. The big benefit here is that CSS3 Transforms can be HW accelerated on iOS devices. This means you can use the GPU to move your character around. This results in very acceptable performance.

The above example will rotate our character 7.5 degrees and move them to x:100 y:100. As discussed in other blog posts we can use a requestAnimationFrame loop to animate this property over time to get HW accelerated performance with a little CSS and JavaScript! Neato…

Apple App Store

iOS is by far the most friendly platform to develop HTML5 games on. However, getting approved as an app developer is probably the most painful. If you are signing up as a business it will require faxing some business documents to apple, paying your $99 fee, and waiting awhile. This will most definitely not happen overnight! If you are planning on launching a game I would give yourself 2 – 3 weeks to be safe.

iOS Background / Multitasking with PhoneGap

PhoneGap has lifecycle events built in for multitasking with pause, resume, etc. I found these events to be unreliable and my app would freeze if iOS decided to randomly dealloc the memory my app was using in the background. I decided to turn off the ability for my application to run in the background. I did however save the state with lawnchair after every turn so that the user could immediately pick up where they left off on the current game even after a phone call or possible crash.

Developing a PhoneGap game for iOS

Since canvas is not HW accelerated on either iOS (edit: canvas now HW accelerated on iOS 5) or android devices I knew from the beginning that all my movements were going to have to be done using CSS3 transforms. Again the added benefit being that on iOS devices CSS3 transforms can be HW accelerated.

SVG – @font-face. If you are planning on using @font-face to jazz up your typography keep in mind that @font-face on iOS 4.1 and below requires SVG fonts to also be included. Otherwise you will get the default serif or sans-serif.

Testing

One neat feature is that you can setup a local domain to test in the iOS simulator before ever opening xcode! You can edit your /etc/hosts file on mac and add an entry such as

Next, you can setup a virtual host in apache to point to this local domain. If you then fire up the iOS simulator, open safari, and navigate to mymobilegame.local you can do initial testing without going through the hassle of setting up an xcode project.

Distribution – App Store

Distribution to the app store with a PhoneGap application is the exact same as any other native iOS application. I won’t go over the whole crazy process. However, make sure to sign your application with your distribution profile before archiving and submitting.

Last but not least. Submit and prey that Apple likes your app and you get approved. Once submitting it will take up to a week for approval. The approval process happens every time you make an update as well so be sure to test your application as you will have to wait a week to fix any bugs!

Android Market

Next up Android. To publish a paid app to the Android Market you will need to pay a one time fee of $25. You will also need to sign up for a google checkout account and wait for them to deposit a small amount into your bank account. You will then need to enter this amount in the developer area to verify. This process shouldn’t take more than a couple days.

Screen Sizes – Phones / Tablets

As you probably already know Android devices come in all shapes and sizes. The goal was to use one codebase for all the different devices on iOS and Android. To account for this Spelling Bees displays all fonts in EM’s. This way they will scale properly on different form factors. Next, be sure that all of your game graphics scale. For example, the bee width and height were based on percentages instead of pixels. This way the bee would have same size ratio on a phone versus a tablet.

Transform Bugs

Unfortunately, Android has a serious bug with CSS3 transforms and only allows one transform at a time. Tip: Use transforms to rotate or scale your object and fall back to animating the top and left properties to translate your object.

Emulator === Pain

When building a game for an Android device the hardest part is testing. The emulator is so painfully slow and makes it impossible to test a game. The only way to adequately test is to find some friends with a bunch of different Android devices. The good news is that you can easily drop your app on their device for testing via the usb cable, or DropBox.

Workflow

With my initial requirement of developing a game once and having it “just work” on the web, as an iOS app, and as an Android app the workflow was very important. Initially the game was developed as any normal website. I setup a web project in eclipse and started coding the basics. Then, I setup a PhoneGap project in Xcode for iOS and an Android based eclipse project. To make the process simple I setup ant targets in my web project. This way I could develop in my web project and could easily publish new features and settings to the different devices without duplicating efforts.

One codebase, 3 projects! WOOT!

Conclusion

With PhoneGap and HTML5 we have a really nice way to write once and deploy to many devices / platforms. With the same codeset I could now also publish to the Chrome Web Store or any other market that comes along that supports HTML5, CSS3, and JavaScript. This give development shops a great way to reduce overhead, leverage existing skill sets, and focus on making fun and engaging games. It is an exciting time to be a JavaScript developer for sure!

Three.js now with 3D Glasses!

I was digging around the Three.js docs on github the other day and saw a reference to a renderer I had not seen before. It was labeled AnaglyphWebGLRenderer. I already knew about the canvas renderer and the WebGL renderer. I thought I would throw it in and give it a try. Changing one line of code from our previous Three.js tutorial I now had a 3D model rendering with support for the old school 3D glasses. Pretty cool! Or a raging headache.

Change this line in the previous Three.js example.

Mr. Bird in Stereo

We make this look good…

Now all you need to do is get your 3D glasses on and check out the new and improved Mr. Bird

1 2