您的位置:首页 > Web前端 > JavaScript

利用Leap Motion+JS 实现简易的隔空网页画板

2016-03-16 01:04 681 查看
你既然看到了这里,就不用解释 leapmotion 了。肯定知道他是干什么的了在网页中,利用 js 和 canvas,能实现简易的画板(手指就是画笔),只能实现一笔画,不能擦除,错了就重画。最难得地方应该是怎么把 LeapMotion 空间中获取的手指的位置映射到网页中。代码如下:
<!DOCTYPE html><html><head><title>This is a test page!</title><meta charset="utf-8"><script src="../leapJs.js"></script><style>#canvas{background-color: #3BFF27;}</style></head><body><canvas id="canvas" width="800" height="600"></canvas><script>var canvas = document.getElementById("canvas");var ctx = canvas.getContext("2d");Leap.loop({frameEventName: "animationFrame"}, function(frame) {<span style="white-space:pre">	</span>for (var i = 0 ;i<frame.gestures.length;i++) {<span style="white-space:pre">	</span>var gesture = frame.gestures[i];<span style="white-space:pre">		</span>switch(gesture.type){<span style="white-space:pre">		</span>case "circle":<span style="white-space:pre">		</span>ctx.clearRect(0, 0, ctx.canvas.width, cx.canvas.height);//画错了就利用手势 circle 重绘画板<span style="white-space:pre">	</span>break;<span style="white-space:pre">	</span>case "swipe":<span style="white-space:pre">		</span>break;<span style="white-space:pre">	</span>default:<span style="white-space:pre">	</span>break;}}<span style="white-space:pre">			</span>//这是关键了,把空间手指坐标映射到网页坐标if (frame.fingers.length>0) {var finger = frame.fingers[1];var position = finger.stabilizedTipPosition;var normalized = frame.interactionBox.normalizePoint(position);<span style="white-space:pre">	</span>var x = ctx.canvas.width * normalized[0];var y = ctx.canvas.height * (1 - normalized[1]);<span style="white-space:pre">	</span>ctx.beginPath();ctx.rect(x, y, 20, 20);ctx.fill();}// 	frame.fingers.forEach(function(finger) {// 	var position = finger.stabilizedTipPosition;//         		var normalized = frame.interactionBox.normalizePoint(position);//          	var x = ctx.canvas.width * normalized[0];//         		var y = ctx.canvas.height * (1 - normalized[1]);//          	ctx.beginPath();//         		ctx.rect(x, y, 20, 20);//         		ctx.fill();// });});</script></body></html>
代码有点混乱。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: