Wednesday, July 11, 2012

jQuery Mobile, PhoneGap, and the Camera Device

One of the great promises of PhoneGap is it ability to access a device's hardware from an easy to code, web-style development environment. In this tutorial we will show how to the device's camera, capture an image, scale it, render it to a page. This tutorial is for iOS, but it should work across devices.

The code in app.js is roughly divided into three parts. The core level Kernel code which dispatches jQuery Mobile events. This code has already been explained in the jQuery Mobile Skeleton Tutorial. 

Next is the Dimensions code. This object consists of two methods, one which dynamically determines the dimensions of the jQuery Mobile page content area. The second which returns those dimensions.

Finally is there is the page code. It has only two externally accessible methods, the handlers for the "pageshow" and "pagehide" events. Most of the app's logic is inside of the "pageshow" event handler. 

Since this is an immediate function, it is executed when the JavaScript parser first encounters it. At that time it caches a few jQuery selectors. This is a performance enhancer since DOM traversal can be time consuming.

Once a "pageshow" event occurs, it calls the Dimension code. It is important to wait for this event since it indicates that jQuery Mobile has rendered, which is necessary for us since when need to determine the size of the header and footer. We use the size of the content area to set the size of the "#picFrame".

The last thing the "pageshow" event handler does is to bind a tap event handler to the "Snap!" button. Inside of the event handler we call PhoneGap's method. Also we do a performance enhancers here as well. I know that event.preventDefault() and return false speed things up by keeping unnecessary code from executing. I am hoping the event.stopPropagation() will also help.

We also bind an event handler to the onload event of the <img> element. When this event is triggered, we use it to get the width and height of the <img>. We then use HTML to scale the image for us. By setting only dimension, HTML will automatically "set" the other for us and maintain the aspect ratio.

That's it for this tutorial. I planned to do at least one more exploring the camera. As always the code for this tutorial is on my GitHub account.

iOS PGCamera on GitHub

For all of you Intellij IDEA fans out there, like me, an Android version of the code available. The HTML/CSS/JavaScript is identical to the iOS version, only the wrapper changes.

Android PGCamera on GitHub