这个根据的是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;