目录
1.deviceMotion的介绍
DeviceOrientation将底层的方向传感器和运动传感器进行了高级封装,提供了DOM事件的支持。其中deviceMotion封装了运动传感器数据的事件,可以获取手机运动状态下的运动加速度等数据。DeviceMotionEvent(设备运动事件)返回设备有关于加速度和旋转的相关信息。
- acceleration属性包含三个加速度属性值{x, y, z};
- accelerationIncludingGravity属性包含三个考虑了重力加速度的加速度属性值{x, y, z}
2.手机坐标系介绍
把手机放在水平的桌面上(屏幕朝上),坐标系就如图中所示,x
轴指向手机的右侧,y
轴指向手机的头部,z
轴垂直于整个手机。该坐标系是相对于手机的,不是相对我们所在的空间的,如果手机的在空间的位置改变了(水平放改为了竖直放),这个时候,手机的这个x,y,z
的坐标系会跟着手机的位置,进行变动的。
3.实现摇一摇的功能
<body>
<img id="myimg" name="" src="" width="300" height="300" alt="">
<script type="text/javascript">
if (window.DeviceMotionEvent) { //判断是否有DeviceMotionEvent事件,如果有就为窗体绑定相关事件
window.addEventListener('devicemotion',deviceMotionHandler,);
}
var speed = 20;//设置一个阈值,触发事件
var x = y = z = lastX = lastY = lastZ = 0;
//监测手机移动的函数
function deviceMotionHandler(eventData) {
var acceleration =eventData.accelerationIncludingGravity;//获取三个考虑了重力加速度的加速度属性值{x, y, z}
x = acceleration.x;
y = acceleration.y;
z = acceleration.z;
if(Math.abs(x-lastX) > speed || Math.abs(y-lastY) > speed ||
Math.abs(z-lastZ) > speed) {
alert("摇一摇,开奖中...");
var myimg=document.getElementById("myimg");//中奖照片
myimg.src="timg.gif";
}
lastX = x;
lastY = y;
lastZ = z;
}
</script>
</body>