Category Archives: HTML5 canvas

Mobile accelerometer “app” using PhoneGap

In my previous post, I explained how to install PhoneGap on a Macbook Pro and test a “Hello World” application on an iOS simulator as well as an actual device. In this post, you will see how easy it is to build a simple mobile application for the iPhone using the PhoneGap framework. Specifically, you will learn how to use the accelerometer and build a simple “app” that will display the instantaneous acceleration of the iPhone in both graphical and text format.

Let’s take a look at the final product. Shown below are a couple of snapshots of the app in action, with the iPhone held in three different orientations. I developed and tested the app for an iPhone 4 (from late 2010). The app should work fine on newer iPhone models as well, although I have not tested this myself. Note that this app will not work on an iOS simulator. You will need an actual iOS device (either iPhone or iPad).

Screen Shot 2014-04-04 at 7.23.56 PM

Observe how the X and Y axes are oriented with respect to the phone. The Z-axis (not shown) points out of the page towards the reader. The coordinate system represented by X-Y-Z always remains fixed with respect to the phone.

The yellow line from the origin can be thought of as an arrow that begins at the origin and points along the direction in which the device is being accelerated. If the phone is stationary, this direction is exactly opposite to what most people understand as the direction of gravitational force (pointing towards the ground). For some more background on the physics of gravity and acceleration, please refer to this article.

Finally, the actual acceleration values along X, Y and Z are printed below the graphics window (yes, the graphics is based on HTML5 canvas) and these numbers are all in units of [m/s2]. You may recall from high school physics that the acceleration due to gravity on the Earth’s surface is approximately 9.8 [m/s2].

Look at the different orientations (a), (b) and (c) in the above picture and make sure you understand what the results mean for each one of them.

Now that we understand everything from the physics point-of-view, let’s get back to the software side of things. The following steps are necessary to build this application:

STEP 1: Install and test PhoneGap (see my previous post)

STEP 2: Create a new project

$ phonegap create accel --name Accelerometer --id com.company.accel

All subsequent PhoneGap commands should be run inside the accel folder.

STEP 3: Add the accelerometer plugin

$ phonegap local plugin add https://git-wip-us.apache.org/repos/asf/cordova-plugin-device-motion.git

STEP 4: Add the HTML5 and JavaScript code

Pull the source code from my GitHub repo using

$ git clone https://github.com/jabhiji/ios-accelerometer-phonegap.git

Move the file “index.html” from the repo folder to the “www” folder of your PhoneGap project.

The basic idea is to get acceleration data from the device every 100 milliseconds and use this data to update the drawing inside the canvas element. The code above is based on some minor modifications to the example code provided on the PhoneGap API documentation. Specifically, it adds the graphical display component using HTML5 canvas.

STEP 5: Build, deploy and run

Like before, all you need to do is:

$ phonegap build ios

followed by

$ phonegap run --device ios

This will compile the code and deploy the application on your device and the run it.

STEP 6: Enjoy your accelerometer!

While all of this can be polished further depending on your individual taste, you are  now all set to test drive this app in any location you can imagine. Drop me a line if you find any bugs or think the results are not accurate or don’t make physical sense.

In summary, we have written a HTML/CSS/JS application and deployed it to an iOS device using PhoneGap.

BOTNIK: the benevolent bomber

My most recent HTML5 game is called BOTNIK: The benevolent bomber.

The name is intended to be a mix of robot and Sputnik-I, the first ever satellite launched by the USSR in 1957. Anyway, the idea is to drop snow bombs on snow monsters. The benevolent part is that the bombs don’t kill the monsters but actually supply them with fuel so that they can float up and escape from Earth.

botnik

If you want to play the game, click on the button above. This post summarizes some of the new things I learned while making this game. You will note that this game reuses some code from my earlier SPACE RACE game, especially the background image (starfield) and the cute little space ship.

Adding transparency to part of your image

In this game, I wanted a fixed background image of stars and wanted a second image (buildings in a city) in “front” of it that moved to the left and right depending on which direction the UFO was going.

I made the city buildings using Keynote and then used the Preview application on my Mac to select and crop the “sky” above the buildings. This essentially makes everything above the buildings completely transparent. In the future, this might also come in handy when working with sprites.

Panning background images

A simple way to implement a background that scrolls to the left and right forever is to offset the background image suitably and then draw the same background image (the city buildings in this case) to the right or left respectively.

This idea is sometimes referred to as tiling. You essentially copy the same pattern along the X-direction in this case. Note that you should be careful to make the background image “periodic” so that the player does not detect sharp gradients between the end of one image and the beginning of the next image.

Turning off default key behavior

In this game, hitting the down arrow key on the keyboard causes the UFO to drop a snow-bomb. However, since we are playing the game in a browser, the down arrow key also implements scrolling of the web-page. We can disable this “default behavior” by using the JavaScript preventDefault() method.

    // down arrow - drop a bomb
    if(e.keyCode == 40)
    {  
        e.preventDefault();
        down_arrow_pressed = true;
    }

Adding gravity

This is relevant for the snow-bomb once it has been dropped. If you want to make the trajectory of the bomb realistic, you need to incorporate the right physics here. Essentially, the horizontal velocity of the bomb continues to be identical to what it was when the bomb was dropped. The vertical velocity (pointing downwards) is initially zero (in this case) and then increases linearly with time because of a constant gravitational acceleration. The path of the bomb turns out to be a parabola.

Hope you have fun playing! I’ll be back with more games soon.

Introduction to HTML5 Games

I recently wrote two simple games that can be played using a modern browser and this post summarizes the experience. Screenshots of the two games are provided below and you can go and play the games before reading any further by clicking on the buttons below the screenshots. Note that both games need a keyboard and you need to be on a laptop or desktop to play.

The first game is called PADDLE. In this, you move a rectangular paddle at the bottom of the game screen and prevent a bouncing ball from escaping. Each time you hit the ball with the paddle, you get 10 points and if the ball escapes, you lose a life.

paddleGame

The second game is SPACE RACE. You are an intrepid space explorer looking for a blue star. You drive a flying saucer and catch as many blue stars as you can while dodging a green space monster who wants to eat you. In addition, you need to be careful not to fall into one of the 4 black holes! Here is a screenshot:

spaceRaceKey

In general, the time interval between the original concept or game idea to a basic but working implementation is really small for HTML5. If you are a perfectionist, you may spend a lot of time in getting the details just right. And you will eventually drill down and optimize or improve specific features. For example, in the SPACE RACE game, my flying saucer was originally a circle. Changing it to look like a flying saucer required some work and some changes to the “collision detection” portion in the code.

You can access the complete source code for both games by pointing your browser to the corresponding .js files. Feel free to use this code as a baseline for writing your own games.

Developing Web Applications using HTML5 canvas

It seems Apple introduced the canvas element almost 10 years ago, in 2004! Alas, I first learned about canvas only recently, while randomly browsing books in the computer programming section at Barnes & Noble. I happened to be browsing books about HTML5, CSS3 and JavaScript for building my website and canvas fit perfectly into my project. After playing with it for a while, it became clear that as far as I was concerned, it was the next QBASIC. Only much better in almost all respects than QBASIC.

The coolest things about canvas is that it can be used to build simple but useful client-side graphics applications that run inside web browsers. These applications can be quite sophisticated, with cross-browser compatibility and a complete point-and-click UI component.

The simple canvas API leads to a quick development cycle. Even if you are completely new to canvas, you will be writing pretty decent graphics apps very quickly. This time will be even shorter if you already know HTML5, CSS3 and JavaScript. Most (if not all) browsers now have dedicated development tools that are useful for debugging and optimizing your (JavaScript) code.

Lastly, canvas apps can be ported to iOS devices using mobile development frameworks like PhoneGap. This means I can create a game using HTML5, CSS3 and JavaScript and play it on my iPhone as if it is a native app. Of course, a better option is to master Objective-C and write a really native app for iPhone and iPad.

On my website, I have some rather simple examples of what canvas can do. These include applications for generating fractals, cellular automata and for a 1D, two-phase lattice Boltzmann method. I plan to spend a lot of time with canvas in the future.