Search code examples
javascriptleap-motion

Moving DIV with Leapmotion


I'm trying to use the leapmotion JS API to move a div around on a website.

I found a tutorial and modified it a bit because it didn't seem to be working.

This is what I've come up with so far, but translation.x is coming up undefined in the console log. Has anyone else messed with the leap JS API?

<!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 controller = new Leap.Controller({enableGestures: true});
var firstValidFrame = null;

      controller.loop(function(frame) {
        if (!firstValidFrame) firstValidFrame = frame;
        var translation = frame.translation(firstValidFrame);
        console.log("X:" + translation.x);
        $('#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>

Solution

  • Two things: 1. The Leap.js library reverted the Vector class that was implemented at one point. So vectors are (again) arrays instead of objects. That makes it translation[0] instead of translation.x. 2. You have to check Frame validity. Objects in the Leap Motion API can be invalid, which means that they are fully formed objects, but have 0/identity properties. This helps avoid lots of undefined objects, but does have a few gotchas. Try checking !firstValidFrame && frame.valid before storing the frame.

    var controller = new Leap.Controller({enableGestures: true});
    var firstValidFrame = null;
    
          controller.loop(function(frame) {
            if (!firstValidFrame && frame.valid) firstValidFrame = frame;
            var translation = frame.translation(firstValidFrame);
            console.log("X:" + translation[0]);
            $('#box').css({marginLeft: translation.x});
          });