如何在Leap Motion框架中获取元素?

时间:2014-06-26 08:41:42

标签: javascript node.js leap-motion

这就是我试图通过WebSocket从Leap Motion设备的帧中获取特定元素的方法。

var webSocket = require('ws');
ws = new webSocket('ws://127.0.0.1:6437');

ws.on('message', function(data, flags) {
    var frame = JSON.parse(data);
    var id = frame.hands;
    var pos = id[0];
    console.log(pos);
});

JSON对象如下所示:Leap Motion Sample Frame

我收到此错误。

Sanjeet-Suhags-MacBook-Pro:LeapJS sanjeetsuhag$ node index.js

/Users/sanjeetsuhag/Developer/Node/LeapJS/index.js:7
    var pos = id[0];
                ^
TypeError: Cannot read property '0' of undefined
    at WebSocket.<anonymous> (/Users/sanjeetsuhag/Developer/Node/LeapJS/index.js:7:14)
    at WebSocket.emit (events.js:98:17)
    at Receiver.self._receiver.ontext (/Users/sanjeetsuhag/Developer/Node/LeapJS/node_modules/ws/lib/WebSocket.js:697:10)
    at Receiver.opcodes.1.finish (/Users/sanjeetsuhag/Developer/Node/LeapJS/node_modules/ws/lib/Receiver.js:397:14)
    at Receiver.expectHandler (/Users/sanjeetsuhag/Developer/Node/LeapJS/node_modules/ws/lib/Receiver.js:384:31)
    at Receiver.add (/Users/sanjeetsuhag/Developer/Node/LeapJS/node_modules/ws/lib/Receiver.js:93:24)
    at firstHandler (/Users/sanjeetsuhag/Developer/Node/LeapJS/node_modules/ws/lib/WebSocket.js:673:22)
    at process._tickCallback (node.js:419:13)

出了什么问题?感谢。

1 个答案:

答案 0 :(得分:0)

如果未检测到指针,hands数组为空,只需将代码更改为:

ws.on('message', function(data, flags) {
    var frame = JSON.parse(data);
    var id = frame.hands;
    if (id.length === 0)
        return;
    var pos = id[0];
    console.log(pos);
});