看到移动端实现摇一摇并振动功能,觉得挺实用便记录了下来。
这个功能主要通过window.DeviceMotionEvent该事件可以监听设备的运动事件,然后通过event.accelerationIncludingGravity获取的x,y,z的位移,通过位置的变化计算设备是否在快速变化加速度以达到监听设备是否在摇一摇的效果,最后利用navigator.vibrate(s)调用触屏手机的震动功能。
整理的代码:
- var shake = (function(){
- var speed = 25; //摇一摇速度的临界值
- var x = y = z = lastX = lastY = lastZ = 0;
- var isShaking = false; //是否在动画中
- return function init(callback){
- if(window.DeviceMotionEvent){
- window.addEventListener('devicemotion', function(){deviceMotionHandler(callback);}, false)
- }else{
- alert("not support mobile motion event");
- }
- }
- function deviceMotionHandler(callback){
- /*获取x,y,z方向的即时速度*/
- var acceleration = event.accelerationIncludingGravity;
- x = acceleration.x;y = acceleration.y;z = acceleration.z;
- if(Math.abs(x-lastX) > speed || Math.abs(y-lastY) > speed || Math.abs(z-lastZ) > speed){
- if(!isShaking){
- //手机震动一秒
- if (navigator.vibrate) {
- navigator.vibrate(1000);
- }else if (navigator.webkitVibrate) {
- navigator.webkitVibrate(1000);
- }
- isShaking = true;
- setTimeout(function(){
- callback();
- isShaking = false;
- },2000);
- }
- }
- lastX = x;lastY = y;lastZ = z;
- }
- }());
- new shake(function(){
- alert("您中奖了!");
- });