原文出处:http://i.jakeyu.top/2016/05/0…
近来要写一个微信网页,须要监听手机动摇事宜,而且陪伴有声响
在HTML5,devicemotion事宜deviceorientation特征的活动传感器的封装时候装配,你能够经由过程转变活动时候猎取装备的状况,加快和其他数据(有另一个角度deviceorientation事宜供应装备,定位等信息)。
<!–more–>
而经由过程DeviceMotion对装备活动状况的推断,则能够协助我们在网页上就完成“摇一摇”的交互结果。
把监听事宜绑定给 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 值在肯定时候范围内 的变化率,即可举行装备是不是有举行晃悠的推断。而为了防备一般挪动的误判,须要给该变化率设置一个适宜的临界 值。
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间的差值的绝对值和时候比率超过了预设的阈值,则推断装备举行 了摇摆操纵。
下面是我改写的代码
<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>