H5实现手机摇一摇

方向事件deviceorientation

该事件实在设备方向发生变化时触发, 使用方法如下;

window.addEventListener('deviceorientation', orientationHandler, true);

回调函数orientationHandler会接收到一个DeviceOrientationEvent类型参数, 包含以下信息.

属性名说明
absolute如果方向数据跟地球坐标系和设备坐标系有差异, 则为true
alpha设备在alpha方向上旋转的角度, 范围为0-360
beta设备在Beta方向上旋转的角度, 范围为-180-180
gamma设备在Gamma方向上旋转的角度, 范围为-90-90

移动事件devicemotion

该事件实在设备位置发生变化时触发

window.addEventListener('devicemotion', motionHandler, false);

该回调函数会接受DeviceMotionEvent类型参数, 包含以下信息.

属性名说明
acceleration设备在X,Y,Z三个轴的方向上移动的距离, 以抵消重力加速度
accelerationIncludingGravity设备在X,Y,Z三个轴方向移动的距离, 包含重力加速度
rotationRate设备在Alpha, Beta, Gamma三个方向旋转的角度
interval从设备获取数据的频率, 单位是毫秒

代码部分

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>摇一摇</title>
</head>
<body>
  <div>
    摇一摇
  </div>
  <script>
    const SHAKE_SPEED = 300;
    let lastTime = 0;//上次变化的时间
    let x = y = z = lastX = lastY = lastZ = 0;//位置变量初始化

    function  motionHandler(event) {
      let acceleration = event.accelerationIncludingGravity;
      let curTime = Date.now();//取得当前时间
      if ((curTime - lastTime) > 120) {
        let diffTime = curTime - lastTime;
        lastTime = curTime;
        x = acceleration.x;
        y = acceleration.y;
        z = acceleration.z;
        //计算摇动速度
        let speed = Math.abs(x + y + z - lastX - lastY - lastZ) / diffTime * 1000;
        if (speed > SHAKE_SPEED) {
          alert("你摇动了手机");
        }
        lastX = x;
        lastY = y;
        lastZ = z;
      }
    }
    if(window.DeviceMotionEvent) {
      window.addEventListener('devicemotion', motionHandler, false);
    } else {
      alert("你的设备不支持位置感应");
    }
  </script>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值