标签:QQ acceleration lastTime curTime var 摇一摇 speed lastX
HTML5提供了访问传感器的API,分别是DeviceOrientationEvent和DeviceMotionEvent
实现方法:
监听devicemotion=>
设备在x,y,z方向上移动的距离和前一次移动的距离之差/两次事件的时间差即设备移动速度=>
与预速度(可通过多次测试取平均值)相比,如果大于之前的预设定值,则发生抖动
html
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>文档标题</title> </head> <body> <h1>Shake your phone</h1> </body> </html>
js
var shake_speed_threshold = 300;//摇动速度阈值 var lastTime = 0;//last change time var x = y = z = lastX = lastY = lastZ;//x,y,z speed initialization function motionHandler(event) { var acceleration = event.accelerationIncludingGravity;//取得包含重力加速的位置信息 var curTime = Date.now();//get the current time if ((curTime - lastTime) > 120) { var diffTime = curTime - lastTime;//difference of the two times lastTime = curTime;//save the time x = acceleration.x; y = acceleration.y; z = acceleration.z; var speed = Math.abs(x + y + z - lastX - lasy - lastZ) / diffTime * 1000;//calulate the speed if (speed > shake_speed_threshold) {//judge the speed is over the pre_speed or not alert("You've shaken the phone!"); } //save the positions lastX = x; lastY = y; lastZ = z; } } if (window.DeviceMotionEvent) { window.addEventListener('devicemotion', motionHandler, false); } else { alert('Your device dose not support the position sensing.'); }
标签:QQ,acceleration,lastTime,curTime,var,摇一摇,speed,lastX 来源: https://www.cnblogs.com/xxxsans/p/14379796.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。