手机摇一摇 事件

这个根据的是DeviceMotionEvent 

DeviceMotionEvent 简 介

1)deviceorientation (设备方向/定位):提供设备的物理方向信息,表示为一系列本地坐标系的旋角。
2)devicemotion (设备运动/手势):提供设备的加速度信息,表示为定义在设备上的坐标系中的笛卡尔坐标,其还提供了设备在坐标系中的自转速率。

3)compassneedscalibration (罗盘校准):用于通知 Web 站点使用罗盘信息校准上述事件。

DeviceMotionEvent 会在设备发生有意义的摆动(或运动)时产生,事件对象封装有产生的间距值,旋转率,和设备加速度

 window.addEventListener("devicemotion", function(event) {
     console.log(event)//
  }, true);

event 4个重要的属性

(1)accelerationIncludingGravity:重力加速度

(2)acceleration:加速度(需要设备陀螺仪支持)

(3)rotationRate(alpha,beat,gamma);旋转速度

(4)interval:获取的时间间隔
然后需要经过计算阈值看是否是在摇一摇动作

 var current = e.accelerationIncludingGravity;
        var currentTime;
        var timeDifference;
        var deltaX = 0;
        var deltaY = 0;
        var deltaZ = 0;
        if ((this.lastX === null) && (this.lastY === null) && (this.lastZ === null)) {
            this.lastX = current.x;
            this.lastY = current.y;
            this.lastZ = current.z;
            return;
        }
        deltaX = Math.abs(this.lastX - current.x);
        deltaY = Math.abs(this.lastY - current.y);
        deltaZ = Math.abs(this.lastZ - current.z);
        if (((deltaX > this.options.threshold) && (deltaY > this.options.threshold)) || ((deltaX > this.options.threshold) && (deltaZ > this.options.threshold)) || ((deltaY > this.options.threshold) && (deltaZ > this.options.threshold))) {
            //计算上次触发摇动到现在的间隔时间
            currentTime = new Date();
            timeDifference = currentTime.getTime() - this.lastTime.getTime();
            if (timeDifference > this.options.timeout) {
                window.dispatchEvent(this.event);
                this.lastTime = new Date();
            }
        }
        this.lastX = current.x;
        this.lastY = current.y;
        this.lastZ = current.z;

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值