Ubuntu logo

Developer

Cordova Camera App Tutorial

Cordova Camera App Tutorial

This tutorial that takes you through the steps needed to create an HTML5 app that uses the Cordova Camera API. It is a simple introduction to using Cordova APIs in your HTML5 apps.

The app we develop here is quite simple:

  • It has a straightforward Ubuntu HTML5 GUI.
  • It provides a Take Picture button.
  • When Take Picture is clicked, the Cordova Camera displays.
  • The user takes a picture.
  • The picture is returned through Cordova and is displayed in the app’s HTML.

Before getting started

HTML5 app basics

This tutorial is not focused on HTML5 app basics. For help, see the HTML5 Guide and the HTML5 ‘Meanings’ App Tutorial.

Ubuntu SDK Tutorials

Some experience with the Ubuntu SDK is helpful. For example, creating an app project and running an app.  For help, see Ubuntu SDK Tutorials.

Cordova guide

You may want to read the Cordova Guide. It is not required reading for this tutorial but does provide some additional information that may be helpful later.

Getting the source for this app

You can obtain the completed source tree for this app as follows:

  1. Open a terminal with Ctrl + Alt + T
  2. Get the branch with:
$ bzr branch lp:ubuntu-sdk-tutorials

After getting the branch, you can find the app code here:

$ cd ubuntu-sdk-tutorials/html5/html5-tutorial-cordova-camera

With these preliminaries out of the way, let’s dive into creating the app itself.

Creating your HTML5 app project

  1. Start by creating an HTML5 app project in the Ubuntu SDK.
  2. During creation, give it whatever name you like, for example: “camera”.

Now, you can run the project from the SDK on the Desktop or on an attached device or emulator.

Note: The emulator may not yet support a camera device. You can run on the Desktop and on an attached physical device.

Tip: You may want to add app project files to revision control such as Bazaar and commit them (except the .user file, which is typically not stored in VCS).

Enable the app for Cordova

As explained in the Cordova Guide, each HTML5 app that uses Cordova provides a set of key Cordova files, including the compiled Cordova runtime and others. When you create an HTML5 app project, it does not contain these files. But, these files can be added to your app from the SDK.

Add the Cordova runtime files into your app project:

Tools > Ubuntu >  Add Cordova runtime to HTML5 project

Now, your project contains some additional files, notably:

  • www/cordova/
  • qml/
  • lib/

Tip: Add these files to your version control system and commit them as appropriate.

Test run the app

If you now run the app, notice that the output contains messages indicating the app is a Cordova app and that various Cordova plugins are enabled. (The output is displayed in the Application Output area of the Ubuntu SDK if you launch with Ctrl + R from the SDK, or in the terminal if you launch using ubuntu-html5-app-launcher –www=www.)

This output demonstrates that the HTML5 app container successfully detects that this app uses (and provides) Cordova.

At this point, the app GUI is still in its default unmodified state. We implement our app GUI a little later.

Import cordova.js into index.html

The next key step for enabling Cordova in your app is to import cordova/cordova.js file into index.html.

The default index.html file contains this import statement, but it is commented out.

Tip: The index.html file and related HTML5 dirs and files are in a www/ directory created with the app.

  1. Find the following in index.html and ensure it is not commented out:
<script src="cordova/cordova.js"></script>

Replace the HTML5 GUI

Here we replace the GUI declared in the default app with one appropriate for this Camera app.

The HTML5 GUI is declared in the <body>…</body>.  This needs to be deleted and replaced, as follows:

  1. In index.html, delete the entire  the <body>…</body> element.
  2. Add the following new <body>…</body> element:
<body>
  <div data-role="mainview">
    <header data-role="header">
      <ul data-role="tabs">
        <li data-role="tabitem" data-page="camera">Camera</li>
      </ul>
    </header>
    <div data-role="content">
      <div data-role="tab" id="camera">
         <div id="loading">
           <header>Loading...</header>
           <progress>Loading...</progress>
         </div>
         <div id="loaded" style="display:none;">
           <button data-role="button" id="click">Take Picture</button>
           <img id="image" src=""/>
         </div>
      </div> <!-- camera -->
    </div> <!-- content -->
  </div> <!-- mainview -->
</body>

This is a simple implementation of an Ubuntu HTML5 app. It declares the following:

  • A mainview div (required)
  • A header with a single tabitem: “Camera”
  • A content div with two internal divs: loading and loaded
  • loading div displays at launch time and includes a progress spinner. This is hidden when Cordova is ready by JavaScript code we look at later
  • loaded div displays when Cordova is ready by JavaScript and contains:
  • A Take Picture button: We create an event listener for this below to popup the Cordova Camera
  • An empty img element: When the camera takes a picture, it uses this element to display the return image

If you run the app now, the GUI appears as follows:

camera.loading.png

As noted above, that is the loading div that displays until Cordova deviceready event is received.

The loaded div that displays when Cordova is ready looks like this:

Let’s take the next step and add the JavaScript that responds to the Cordova deviceready event by hiding the loading div, displaying the loaded div, and providing an event handler for the Take Picture button.

Adding JavaScript to display the Cordova Camera

Here we add an event handler for the Cordova deviceready event and, inside that code, sets up our Take Picture to call the Cordova Camera API to let the user take a picture.

  1. The first step is to delete all JavaScript in www/js/app.js after the UbuntuUI object is created and initialized. So make your whole app.js file look like this:
window.onload = function () {
   var UI = new UbuntuUI();
   UI.init();
== DELETE ALL THIS ==
};
  1. Now, copy the following event listener code in after the UI.init(); line:
window.onload = function () {
   var UI = new UbuntuUI();
   UI.init();
/* HERE’S THE NEW CODE: */
   document.addEventListener("deviceready", function() {
       if (console && console.log)
           console.log('Platform layer API ready');
       //hide the loading div and display the loaded div
       document.getElementById("loading").style.display = "none";
       document.getElementById("loaded").style.display = "block";
       // event listener to take picture
       UI.button("click").click( function() {
            navigator.camera.getPicture(onSuccess, onFail, {
                quality: 100,
                targetWidth: 400,
                targetHeight: 400,
                destinationType: Camera.DestinationType.DATA_URL,
                correctOrientation: true
            });
          console.log("Take Picture button clicked");
       }); // "click" button event handler
     }, false); // deviceready event handler
/* END OF NEW CODE */
};

This is the first bit of new code that’s needed. Let’s take a look at it.

Examining the new event listener

  • An event handler for the Cordova deviceready event is added. This is received when the Cordova system is fully loaded and ready, so this is a great place to put code that uses Cordova objects. (See Cordova Guide for information.)
  • Inside the deviceready handler, first the loading div is hidden and then then loaded div is displayed.
  • Then, the Take Picture button is obtained with: UI.button(“click”).
  • Its click(FUNCTION) method provides the FUNCTION that runs when the button is clicked, the button’s event handler code. (See HTML5 APIs for complete API reference docs.)
  • This event handling function calls the navigator.camera.getPicture(…) method.
  • The navigator object is the base Cordova object and is available in the HTML5 runtime container when the app includes Cordova as described above.
  • getPicture(…) takes three arguments: the name of the function to run when a picture is taken(this is called onSuccess here and is defined below), the name of a function to run when an attempt to take a picture fails (onFail here, defined below), and some optional arguments.
  • In the optional arguments, we set the image quality, its size, the type of image returned to DATA_URL, which enables passing the image directly in JavaScript as a base64 encoded piece of data (without saving it as a file), and enable orientation correction

Tip: The getPicture(…) method and its arguments are defined in the Cordova API reference docs.

Defining the onSuccess function

As we saw above, Cordova getPicture is told to run onSuccess when the picture is taken. Cordova runs it and passes it the actual picture, formatted as Cordova type DATA_URL.

So this app:

  • Needs an onSuccess function
  • That receives the passed image data
  • And modifies the app’s HTML img element’s src attribute to actually display the image from the passed image data

Here is code that does these things. You can paste this into the bottom of app.js:

function onSuccess(imageData) {
   var image = document.getElementById('image');
   image.src = "data:image/jpeg;base64," + imageData;
   image.style.margin = "10px";
   image.style.display = "block";
}

Defining the onFailure function

For this simple app, we simply log the message provided by Cordova to console. Paste this at the bottom of app.js:

function onFail(message) {
   console.log("Picture failure: " + message);
}

Running the app

With these pieces in place, the app should run and allow you to take a picture.

For example, run it on the desktop with Ctrl + R. You might also want to use the other methods for running an app described in the Ubuntu SDK section.

Here is how the Cordova camera looks running on the Desktop after clicking Take Picture:

And here’s how the app looks finally, after that picture is returned through JavaScript and displayed in the HTML:

camera4.png

Polish

Add CSS

Let’s add some CSS styling:

  • Make our Take Picture button Ubuntu orange
  • Center it
  • Center the “Loading…” progress spinner

Create www/app.css with this content:

#loading {
  position: absolute;
  left:45%;
}
#loaded {
  display: none;
}

Now, in index.html, simply add the following inside the <head>

<link href="app.css" rel="stylesheet" type="text/css" />

Now, the Loading page and the home page look like this:

camera.loading.centered.png
camera-take-picture-wide-button.png

Desktop file for presentation in Unity

Apps always need some final packaging and polish. For example, take a look at the desktop file. This provides important parts that Unity uses to display the app, including:

  • Name: Give the app a short name
  • Icon: Add an icon for the app and state the file name here (you can grab one from the source branch named cordovacam.png)

Manifest.json

And, the manifest.json file provides key information used to build the click packag. Although this is simply a sample app, real apps get published for others to install, and the manifest provides key data such as the maintainer, the app’s unique ID, and more.

Next steps

Check out the Cordova Guide for a high level review of using Cordova in Ubuntu HTML5 apps and for adding Ubuntu as a built platform for native Cordova projects.

The Cordova APIs give your HTML5 apps access to other system and device-level things, so check these out by visiting the Cordova API docs.