For those who don’t know Leap Motion is a 3D gesture controller that captures your hands and fingers movements.

playing Jenga with the Leap Motion
One cool thing the Leap Motion guys did was to create a JavaScript Client Library which allows us to capture the device data in a html page.
Since I don’t have a glass monitor like in Minority Report or 3d holograms like Tony Stark has, I though I’d be cool to use a browser and the Leap Motion to manipulate DOM objects.
So let’s say we have a DIV like this one:
1 | <div id="box" style="width: 200px; border: 1px solid #666666; padding: 10px 10px 70px 10px; display: inline-block;"></div> |
And now we don’t want to move it with our thoughts because that’s impossible but instead with our hands:
First thing to do -obviously- is include the Leap Motion JS lib.
Secondly, we need to capture the frames data the device is sending us through the Leap.loop event function:
1 2 3 4 | Leap.loop(function(frame) { console.log("Frame:" + frame); }); |
Third step is to capture the current frames vectors [x,y,z] and use this information to manipulate DOM objects. The way to do this is to track the position derived from the motion between a first frame and the current frame:
1 2 3 4 5 6 7 8 9 | var firstValidFrame = null Leap.loop(function(frame) { // use first frame as comparison if (!firstValidFrame) firstValidFrame = frame; var translation = frame.translation(firstValidFrame); console.log("X:" + translation.x); }); |
Now the fun part! As you can see we could grab the x coordinate with translation.x (in millimiters) – on the same way we could do with the coordinates y and z.
By using the x coordinates we can manipulate the DIV marginLeft CSS property and simulate as if the user were moving the DIV with her hand.
If you have the Leap Motion try this full example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf8"> <title></title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <script src="leap.js"></script> </head> <body> <script> var firstValidFrame = null Leap.loop(function(frame) { // use the first frame to serve as comparison if (!firstValidFrame) firstValidFrame = frame; var translation = frame.translation(firstValidFrame); $('#box').css({marginLeft: translation.x}); }); </script> <div id="box" style="width: 200px; border: 1px solid #666666; padding: 10px 10px 70px 10px; display: inline-block"></div> </body> </html> |
Don’t have a Leap Motion? Pre order it!






Contact me