手机摇一摇实现

2017-12-13  本文已影响0人  记忆是条狗
/**
 * @file 摇一摇移 动事件devicemotion(设备运动事件)
 * @name devicemotion
 * @desc 支持设备移动事件devicemotion(设备运动事件)返回设备有关于加速度和旋转的相关信息。 
 *       加速度的数据将包含三个轴:x,y和z(x轴横向贯穿手机屏幕或者笔记本键盘,y轴纵向贯穿手机屏幕或笔记本键盘,z轴垂直于手机屏幕或笔记本键盘) 
 * @import lib/zeptov1.0.js
 */
$(function () {
    //摇一摇设置
    $.SHAKE = {
        SHAKE_THRESHOLD : 2000,
        last_x : 0,
        last_y : 0,
        last_z : 0,
        lastUpdate : 0,
        sharkTimer : null
    };
    //摇一摇模拟实现
    $.deviceMotionHandler = function(e){
        var me = $.SHAKE;
        var x;
        var y;
        var z;
        var acceleration = e.accelerationIncludingGravity;
        var l;
        var currentTime = new Date().getTime();
        if ((currentTime - me.lastUpdate) > 100) {
            var passTime = (currentTime - me.lastUpdate);
            me.lastUpdate = currentTime;
            x = acceleration.x;
            y = acceleration.y;
            z = acceleration.z;
            var c = Math.abs(x + y + z - me.last_x - me.last_y - me.last_z) / passTime * 10000;
            if (c > me.SHAKE_THRESHOLD) {
                me.sharkTimer && clearTimeout(me.sharkTimer);
                me.sharkTimer = setTimeout(function() {  
                  shake(); 
                }, 300);
            }
            me.last_x = x;
            me.last_y = y;
            me.last_z = z;
        }
    };
});
//摇一摇初始化
if (window.DeviceMotionEvent) {
  var rocktip = $(".rocktip");
  rocktip.removeClass("none");
  window.addEventListener("devicemotion", function() { $.deviceMotionHandler.apply(null, arguments)}, false);
}
function shark(){
  //todos
}
上一篇下一篇

猜你喜欢

热点阅读