最近要写一个微信网页,须要监听手机摇动事件,而且伴随有声音html
在HTML5,devicemotion事件deviceorientation特性的运动传感器的封装时间装置,你能够经过改变运动时间获取设备的状态,加速和其余数据(有另外一个角度deviceorientation事件提供设备,定位等信息)。微信
<!--more-->code
而经过DeviceMotion对设备运动状态的判断,则能够帮助咱们在网页上就实现“摇一摇”的交互效果。htm
把监听事件绑定给 deviceMotionHandler事件
if (window.DeviceMotionEvent) { window.addEventListener('devicemotion', deviceMotionHandler, false); } else { alert('本设备不支持devicemotion事件'); } 获取设备加速度信息 accelerationIncludingGravity function deviceMotionHandler(eventData) { var acceleration = eventData.accelerationIncludingGravity, x, y, z; x = acceleration.x; y = acceleration.y; z = acceleration.z; document.getElementById("status").innerHTML = "x:"+x+"<br />y:"+y+"<br />z:"+z; }
“摇一摇”的动做既“必定时间内设备了必定距离”,所以经过监听上一步获取到的x, y, z 值在必定时间范围内 的变化率,便可进行设备是否有进行晃动的判断。而为了防止正常移动的误判,须要给该变化率设置一个合适的临界 值。ip
var SHAKE_THRESHOLD = 800; var last_update = 0; var x = y = z = last_x = last_y = last_z = 0; if (window.DeviceMotionEvent) { window.addEventListener('devicemotion', deviceMotionHandler, false); } else { alert('本设备不支持devicemotion事件'); } function deviceMotionHandler(eventData) { var acceleration = eventData.accelerationIncludingGravity; var curTime = new Date().getTime(); if ((curTime - last_update) > 100) { var diffTime = curTime - last_update; last_update = curTime; x = acceleration.x; y = acceleration.y; z = acceleration.z; var speed = Math.abs(x + y + z - last_x - last_y - last_z) / diffTime * 10000; var status = document.getElementById("status"); if (speed > SHAKE_THRESHOLD) { doResult(); } last_x = x; last_y = y; last_z = z; } }
100毫秒进行一次位置判断,若先后x, y, z间的差值的绝对值和时间比率超过了预设的阈值,则判断设备进行 了摇晃操做。get
<audio style="display: none;" src="http://xunlei.sc.chinaz.com/files/download/sound1/201410/5018.mp3" id="musicBox" preload="preload" controls></audio>
<script> var SHAKE_THRESHOLD = 3000; var last_update = 0; var x=y=z=last_x=last_y=last_z=0; var media; media= document.getElementById("musicBox"); function init(){ last_update=new Date().getTime(); if (window.DeviceMotionEvent) { window.addEventListener('devicemotion',deviceMotionHandler, false); } else{ alert('not support mobile event'); } } function deviceMotionHandler(eventData) { var acceleration =eventData.accelerationIncludingGravity; var curTime = new Date().getTime(); if ((curTime - last_update)> 100) { var diffTime = curTime -last_update; last_update = curTime; x = acceleration.x; y = acceleration.y; z = acceleration.z; var speed = Math.abs(x +y + z - last_x - last_y - last_z) / diffTime * 10000; if (speed > SHAKE_THRESHOLD) { media.play(); } last_x = x; last_y = y; last_z = z; } } window.onload = function(){ init(); } </script>