手机摇一摇的实现和兼容

手机摇一摇,授权重力感应要在https环境下面测试

  • 判断是否支持手机摇一摇
    • ios 13+ 的系统需要先授权才能摇动,获取权限需要点击事件才能触发
 function addShakeEvent() {
     // 判断是否支持摇动
     if (window.DeviceMotionEvent) {
         var ua = navigator.userAgent.toLowerCase();
         if (ua.indexOf("like mac os x") > 0) {  //ios
             var reg = /os [\d._]*/gi;
             var verinfo = ua.match(reg);
             var version = (verinfo + "").replace(/[^0-9|_.]/ig, "").replace(/_/ig, ".");
             var arr = version.split(".");
             if (version>13.2) {  //对13.3以后的版本处理,包括13.3,
                 DeviceMotionEvent.requestPermission().then(function (permissionState) {
                     if (permissionState === 'granted') {//已经授权过的,可以摇动手机
                         addCheckShake();
                     }else {//还未授权过的,弹出授权弹窗
                         $('#iosPop').show();
                     }
                 }).catch(function (err) {
                       alert(error)
                 });
             } else {  //13.3以前的版本
                 addCheckShake();
             }
         } else {  // 处理常规的非iOS 13+设备
             addCheckShake();
         }
     } else {
         alert('您的手机不支持摇晃功能,请更换手机再尝试吧');
     }
 }
  • ios同意授权按钮点击
$('#btnIosGranted').on('click', function (e) {
    e.preventDefault();
    $('#iosPop').hide();
    ios13granted();
});
  • ios 13+ 的系统授权摇一摇
function ios13granted() {
    if (typeof DeviceMotionEvent.requestPermission === 'function') {
        DeviceMotionEvent.requestPermission().then(function (permissionState) {
            if (permissionState === 'granted') {
                addCheckShake();
            }
        }).catch(function (error) {
            alert(error)
        })
    } else {    // 处理常规的非iOS 13+设备
        addCheckShake();
    }
};
  • 手机摇一摇
function addCheckShake() {
    var SHAKE_THRESHOLD = 3000; // 摇动阈值
    var last_update = 0;
    var x, y, z, last_x = 0,
        last_y = 0,
        last_z = 0;
    // 判断是否支持摇动
    window.addEventListener('devicemotion', deviceMotionHandler, false);
    //摇动函数
    function deviceMotionHandler(eventData) {
        var acceleration = eventData.accelerationIncludingGravity;
        var curTime = new Date().getTime();
        if ((curTime - last_update) > 10) {
            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) {
                getshakePrize();
            }
            last_x = x;
            last_y = y;
            last_z = z;
        }
    }

}
posted @ 2021-02-22 16:48  黄哈哈。  阅读(292)  评论(0编辑  收藏  举报