Asial Blog

Using Leap Motion and PhoneGap (Cordova)

Category :
Monaca
Tags :
Monaca
Tech
JavaScript
社長BLOG
HTML5
Hi there. Today I want to introduce one of my new digital gadget, Leap Motion. Maybe many of the gadget-lovers already know, Leap Motion is a small stick-size device that captures your hands motion and send it to the host computer. It is like a Kinect, but have simpler SDK, and more affordable.

The usual case to use Leap Motion is to plug it to your PC, and drive some apps that supports it. Leap Motion allows third party developers to build apps that support Leap Motion. It includes, traditional C++ based SDK for Windows and Mac, and a JavaScript SDK for Web app developers.

JavaScript? Yes. It means, combined with PhoneGap, you can develop a mobile app to access to this new device with your favorite technology. So, this article will explain the overview and some sample application with Leap Motion.

How can a PhoneGap app connect to Leap Motion?



Leap Motion will be connected via USB to the host computer. So you are actually connecting to the PC from your PhoneGap app. When you install Leap Motion driver, it will automatically setup a daemon program running on your PC that opens and listens to its WebSocket protocol. Then, your app will connect using HTML5 WebSocket client to the host, via Leap Motion JavaScript API.

Since WebSocket client is required for the connection, Android devices cannot meet this requirement. Therefore, throughout this article I am using my iPad to run sample apps.

Leap Motion SDK



Leap Motion JavaScript SDK is open-source, and can be found in official website. I suggest you to read through the getting started guide, since it describes important aspect of how it is communicating with your app. In a nutshell, through WebSocket connection, it will send user’s interaction data at the specified frequency (default: 60fps), including the raw coordinates and the gesture commands calculated by the hardware. The recognizable gestures include Key Tap (like tapping to your keyboard), Screen Tap, Swipe, and Circle. Also, the device is smart enough to detect each individual fingers and its movement (like velocity).

Okey, now you are ready to create a new Leap Motion enabled app. In this article, I use Monaca for development environment. If you first hear about Monaca, it is a browser-based development environment for PhoneGap, which provides all-in-one IDE and cloud services. It is free to use, so please register an account if you don’t have one yet.

Hello Leap Motion!



Now let’s create very first example. Create a new project from “Minimum Template”, and IDE will display like below.



Then change your index.html as follows:

  1. <html>
  2.   <head>
  3.     <script src="plugins/plugin-loader.js"></script>
  4.     <link rel="stylesheet" href="plugins/plugin-loader.css">
  5.     <style>
  6.       #motion {
  7.         box-sizing: border-box;
  8.         position: absolute;
  9.         top: 30%; left: 20%; width: 60%;
  10.         opacity: 0.9;
  11.         background-color: #fff;
  12.         padding: 30px;
  13.         border: 1px solid #ccc;
  14.         border-radius: 20px;
  15.         text-align: center;
  16.         font-size: 30px;
  17.       }
  18.     </style>
  19.     <script src="http://js.leapmotion.com/0.2.0-beta1/leap.min.js"></script>
  20.     <script>
  21.     monaca.viewport({"width": "640"});
  22.     Leap.loop({
  23.       enableGestures: true,
  24.       host: '10.0.5.130' // CHANGE HERE!!
  25.     }, function(obj) {
  26.       if (obj.gestures) {
  27.         obj.gestures.forEach(function(gesture) {
  28.           if (gesture.state == "start") {
  29.             $("#motion").text(gesture.type).show();
  30.             lastGestureType = gesture.type;
  31.             addList(gesture);
  32.           } else if (gesture.state == "stop") {
  33.             $("#motion").fadeOut();
  34.           }
  35.         });
  36.       }
  37.     });
  38.     function addList(json) {
  39.       var $list = $("#gestures");
  40.       $list.prepend("<li class='ui-li ui-li-static'><b>Starting " + json.type + "</b> <div style='font-size: 80%'>" + json + "</div></li>")
  41.     }
  42.     </script>
  43.   </head>
  44.   <body>
  45.     <div data-role="page">
  46.       <div data-role="header" data-position="fixed"><h1>Leap Motion Gestures</h1></div>
  47.       <div class="ui-listview" id="gestures"></div>
  48.     </div>
  49.     <div id="motion" style="display: none"></div>
  50.   </body>
  51. </html>

Now, please change the host address (mentioned as // CHANGE HERE!! in the source code) to your computer’s IP address. The server should be running if Leap Motion driver is installed.

The program code should be self-explanatory. The function “Leap.loop” is the most important function, where the callback function will be triggered at maximum of 60 times per second, and display the output of the gesture found.

If you are first-comer to Monaca, you just download Monaca Debugger via App Store to execute this program. Please try.

Here is the screenshot of the result of this program. It dumps out the raw data, and displays motion while detecting in front.



More Complex Example



Now, let’s create a more complex example. Replace index.html with following code:

  1. <html>
  2.   <head>
  3.     <title>DOM Visualizer - Leap</title>
  4.     <script src="http://js.leapmotion.com/0.2.0-beta1/leap.min.js"></script>
  5.     <script>
  6.  
  7.       function moveFinger(Finger, posX, posY, posZ, dirX, dirY, dirZ) {
  8.         Finger.style.webkitTransform = "translateX("+posX+"px) translateY("+posY+"px) translateZ("+posZ+"px) rotateX("+dirX+"deg) rotateY(0deg) rotateZ("+dirZ+"deg)";
  9.       }
  10.  
  11.       function moveSphere(Sphere, posX, posY, posZ, rotX, rotY, rotZ) {
  12.         Sphere.style.webkitTransform = "translateX("+posX+"px) translateY("+posY+"px) translateZ("+posZ+"px) rotateX("+rotX+"deg) rotateY(0deg) rotateZ(0deg)";
  13.       }
  14.  
  15.       var fingers = {};
  16.       var spheres = {};
  17.       Leap.loop({
  18.         enableGestures: true,
  19.         host: '10.0.5.130' // CHANGE HERE!!
  20.       }, function(frame) {
  21.         var fingerIds = {};
  22.         var handIds = {};
  23.         if (frame.hands === undefined ) {
  24.           var handsLength = 0
  25.         } else {
  26.           var handsLength = frame.hands.length;
  27.         }
  28.  
  29.         for (var handId = 0, handCount = handsLength; handId != handCount; handId++) {
  30.           var hand = frame.hands[handId];
  31.           var posX = (hand.palmPosition[0]*3);
  32.           var posY = (hand.palmPosition[2]*3)-200;
  33.           var posZ = (hand.palmPosition[1]*3)-400;
  34.           var rotX = (hand._rotation[2]*90);
  35.           var rotY = (hand._rotation[1]*90);
  36.           var rotZ = (hand._rotation[0]*90);
  37.           var sphere = spheres[hand.id];
  38.           if (!sphere) {
  39.             var sphereDiv = document.getElementById("sphere").cloneNode(true);
  40.                 sphereDiv.setAttribute('id',hand.id);
  41.                 sphereDiv.style.backgroundColor='#'+Math.floor(Math.random()*16777215).toString(16);
  42.                 document.getElementById('scene').appendChild(sphereDiv);
  43.                 spheres[hand.id] = hand.id;
  44.           } else {
  45.             var sphereDiv =  document.getElementById(hand.id);
  46.             if (typeof(sphereDiv) != 'undefined' && sphereDiv != null) {
  47.               moveSphere(sphereDiv, posX, posY, posZ, rotX, rotY, rotZ);
  48.             }
  49.           }
  50.           handIds[hand.id] = true;
  51.         }
  52.         for (handId in spheres) {
  53.           if (!handIds[handId]) {
  54.             var sphereDiv =  document.getElementById(spheres[handId]);
  55.             sphereDiv.parentNode.removeChild(sphereDiv);
  56.             delete spheres[handId];
  57.           }
  58.         }
  59.  
  60.         for (var pointableId = 0, pointableCount = frame.pointables.length; pointableId != pointableCount; pointableId++) {
  61.           var pointable = frame.pointables[pointableId];
  62.           var posX = (pointable.tipPosition[0]*3);
  63.           var posY = (pointable.tipPosition[2]*3)-200;
  64.           var posZ = (pointable.tipPosition[1]*3)-400;
  65.           var dirX = -(pointable.direction[1]*90);
  66.           var dirY = -(pointable.direction[2]*90);
  67.           var dirZ = (pointable.direction[0]*90);
  68.           var finger = fingers[pointable.id];
  69.           if (!finger) {
  70.             var fingerDiv = document.getElementById("finger").cloneNode(true);
  71.                 fingerDiv.setAttribute('id',pointable.id);
  72.                 fingerDiv.style.backgroundColor='#'+Math.floor(Math.random()*16777215).toString(16);
  73.                 document.getElementById('scene').appendChild(fingerDiv);
  74.                 fingers[pointable.id] = pointable.id;
  75.           } else {
  76.             var fingerDiv =  document.getElementById(pointable.id);
  77.             if (typeof(fingerDiv) != 'undefined' && fingerDiv != null) {
  78.               moveFinger(fingerDiv, posX, posY, posZ, dirX, dirY, dirZ);
  79.             }
  80.           }
  81.           fingerIds[pointable.id] = true;
  82.         }
  83.         for (fingerId in fingers) {
  84.           if (!fingerIds[fingerId]) {
  85.             var fingerDiv =  document.getElementById(fingers[fingerId]);
  86.             fingerDiv.parentNode.removeChild(fingerDiv);
  87.             delete fingers[fingerId];
  88.           }
  89.         }
  90.         document.getElementById('showHands').addEventListener('mousedown', function() {
  91.           document.getElementById('app').setAttribute('class','show-hands');
  92.         }, false);
  93.         document.getElementById('hideHands').addEventListener('mousedown', function() {
  94.           document.getElementById('app').setAttribute('class','');
  95.         }, false);
  96.       });
  97.  
  98.     </script>
  99.     <style>
  100.       *,*:before,*:after {
  101.         margin: 0;
  102.         padding: 0;
  103.         border: 0;
  104.         -webkit-box-sizing: border-box;
  105.       }
  106.       button {
  107.         padding: .5em;
  108.       }
  109.       #app {
  110.         position: absolute;
  111.         width: 100%;
  112.         height: 100%;
  113.         font-size: 200%;
  114.         overflow: hidden;
  115.         background-color: #101010;
  116.         -webkit-perspective: 1000;
  117.       }
  118.       #scene,
  119.       #scene:before {
  120.         position: absolute;
  121.         left: 50%;
  122.         top: 50%;
  123.         width: 40em;
  124.         height: 40em;
  125.         margin: -20em 0 0 -20em;
  126.         border: 4px solid #A0A0A0;
  127.         background-color: rgba(255,255,255,.1);
  128.         background-image:
  129.         -webkit-linear-gradient(rgba(255,255,255,.4) .1em, transparent .1em),
  130.         -webkit-linear-gradient(0deg, rgba(255,255,255,.4) .1em, transparent .1em),
  131.         -webkit-linear-gradient(rgba(255,255,255,.3) .05em, transparent .05em),
  132.         -webkit-linear-gradient(0deg, rgba(255,255,255,.3) .05em, transparent .05em);
  133.         background-size: 5em 5em, 5em 5em, 1em 1em, 1em 1em;
  134.         background-position: -.1em -.1em, -.1em -.1em, -.05em -.05em, -.05em -.05em;
  135.         -webkit-transform-style: preserve-3d;
  136.         -webkit-transform: rotateX(75deg);
  137.       }
  138.       #scene {
  139.         -webkit-transform: rotateX(75deg);
  140.       }
  141.       #scene:before {
  142.         content: '';
  143.         -webkit-transform: rotateX(90deg) translateZ(19.5em) translateY(20em);
  144.       }
  145.       .cube {
  146.         background-color: red;
  147.         -webkit-transform-style: preserve-3d;
  148.         -webkit-transform: translateX(19.5em) translateY(19.5em) translateZ(0em);
  149.       }
  150.       .finger,
  151.       .sphere {
  152.         position: absolute;
  153.         left: 50%;
  154.         top: 50%;
  155.         width: 1em;
  156.         height: 1em;
  157.         margin: -.5em 0 0 -.5em;
  158.         -webkit-transform-style: preserve-3d;
  159.         -webkit-transform: translateX(14.5em) translateY(14.5em) translateZ(0);
  160.       }
  161.  
  162.       .finger {
  163.         opacity: .8;
  164.         height: 3em;
  165.       }
  166.  
  167.       .sphere {
  168.         opacity: .3;
  169.         display: none;
  170.         font-size: 100px;
  171.       }
  172.  
  173.       .show-hands .sphere {
  174.         display: block;
  175.       }
  176.  
  177.       .face {
  178.         position: absolute;
  179.         width: 1em;
  180.         height: 1em;
  181.         background-color: inherit;
  182.         -webkit-transform-style: preserve-3d;
  183.         -webkit-transform-origin: 0 0;
  184.         -webkit-box-shadow: inset 0 0 0 1px rgba(255,255,255,.9);
  185.       }
  186.       .cube .face.tp { -webkit-transform: translateZ(1em); }
  187.       .cube .face.ft { -webkit-transform: rotateX(90deg) translateZ(-1em); }
  188.       .cube .face.bk { -webkit-transform: rotateX(90deg); }
  189.       .cube .face.lt { -webkit-transform: rotateY(90deg) translateX(-1em); }
  190.       .cube .face.rt { -webkit-transform: rotateY(90deg) translateX(-1em) translateZ(1em); }
  191.  
  192.       .finger .face.tp { -webkit-transform: translateZ(1em); height: 3em; }
  193.       .finger .face.ft { -webkit-transform: rotateX(90deg) translateZ(-3em); }
  194.       .finger .face.bk { -webkit-transform: rotateX(90deg); }
  195.       .finger .face.lt { -webkit-transform: rotateY(90deg) translateX(-1em); height: 3em;}
  196.       .finger .face.rt { -webkit-transform: rotateY(90deg) translateX(-1em) translateZ(1em); height: 3em;}
  197.  
  198.     </style>
  199.   </head>
  200.   <body>
  201.     <div id="app" class="show-hands">
  202.       <button id="showHands">Show Hands</button>
  203.       <button id="hideHands">hide Hands</button>
  204.       <div id="scene">
  205.         <div id="cube" class="cube">
  206.           <div class="face tp"></div>
  207.           <div class="face lt"></div>
  208.           <div class="face rt"></div>
  209.           <div class="face ft"></div>
  210.           <div class="face bk"></div>
  211.         </div>
  212.         <div id="finger" class="cube finger">
  213.           <div class="face tp"></div>
  214.           <div class="face lt"></div>
  215.           <div class="face rt"></div>
  216.           <div class="face ft"></div>
  217.           <div class="face bk"></div>
  218.         </div>
  219.         <div id="sphere" class="cube sphere">
  220.           <div class="face tp"></div>
  221.           <div class="face lt"></div>
  222.           <div class="face rt"></div>
  223.           <div class="face ft"></div>
  224.           <div class="face bk"></div>
  225.         </div>
  226.       </div>
  227.     </div>
  228.   </body>
  229. </html>

I post the example movie taken by this sample. You will notice Leap Motion is detecting five individual fingers seamlessly.



This sample app is a slightly modification version of this page.

From Here



It is up to you to make this cool technology integrated with your mobile apps. The only pitfall is that you need a PC running as a server. I hope next Leap Motion will have its own WiFi connection and a WebSocket server.

You can actually go far beyond the examples here. If you have made a Leap Motion PhoneGap app with Monaca, please inform us so that we can feature on our blog.

Happy coding!