Leap Motion Controller JS Experiments

I finally found a few minutes to play around with the Leap motion controller that has been sitting on my desk for slightly over a month now. Yes, I know, pretty pathetic but hey - I'd like to see you do better with a newborn around the house.

I am not going to cover the installation of the controller itself, so we'll start with an installed controller ready to play in the browser. If you do need to read up the installation take a at the Leap Motion Developer Documentation.

First things first, we need to include the LeapJS library which is version 0.2.0 at the time of this writing. You can either get it from the leapjs github repository or you source it directly.

The API Reference is available online so I'm not going to go into detail. What I want to try as a first experiment is to track my fingers on the screen. Nothing fancy, really just a few circles on the screen which are moving along when I move my fingers. The API gives us a number of classes to deal with your hand, different pointer objects including fingers and gestures of various kinds. For what I'm doing we'll really only need to deal with frames and pointables.

You might be wondering how to get the data from the controller as we are apparently using only two classes that encapsulate that data. Outside the browser we would indeed have to instantiate our own controller and poll it for frames like so:

var Leap = require('leapjs');

var controller = new Leap.Controller({
  enableGestures: 'true',
  frameEventName: 'deviceFrame'
});

controller.on('frame', function(frame){
  // console.log("Frame: " + frame.id + " @ " + frame.timestamp + " valid: " + frame.valid);
  if(frame.valid && frame.gestures.length > 0) {
    console.log(frame.dump());
  }
});

controller.connect();

In the browser however there is an easier way. We can simply use Leap.loop which is a method that takes a callback function and used the browser's requestAnimationFrame to pass it 60fps of motion data.

Setting up the canvas happens on lines 3-13 and is really no biggie. No magic here, pretty much business as usual.

In order to draw something on the screen we'll need a method to do just that and we'll conveniently call it draw (lines 16-41) which at the very end we're passing to Leap.loop as the callback.

And that's really it. Surprisingly simple. If you have a controller yourself and would like to see it in action check the JSBin here, else here's a screengrab:

© 2013-2014 Henning Hoyer