github - /public/js/tools/play/shake
import shake from "./shake.js";
let shake = new shake();
//会默认启动监听,如果需要二次启动必须使停止监听以后
shake.stop(); //移除监听
shake.start();//开始监听
//let shake = new shake({step:300,stopTime:3000})
参数 | 说明 | 例子 |
---|---|---|
step | 晃动力度 | {step:300}默认300 |
stopTime | 结束时常 | {stopTime:3000�}默认3000 |
event | 事件监听 | start,actio,stop |
start | 开始 | on("start",fn) |
actio | 摇动中 | on("action",fn) |
stop | 结束 | on("stop",(number,th)=>{}) |
number,th | number:摇动次数 | th: 当前指针 |
/**
* 摇一摇
* @class shake
* let shake = new shake({step:300,stopTime:3000})
* step:晃动力度
* stopTime:停止时常
* event: start action stop
* shake.on("start",(number,this))
* number: 摇动次数
* this: shake类
*/
class shake{
constructor(arg){
this.mot={
step:300, //摇动力度
stopTime:3000,//秒停止
last_update: 0,
x:0,
y:0,
z:0,
last_x:0,
last_y:0,
last_z:0,
pow:1
}
this.time=0;
Object.assign(this.mot,arg);
this.bindEvent();
this.handEvent=[];//记录
this.check=1;//是否启动中
}
setTime=()=>{
clearTimeout(this.time);
this.time = setTimeout(arg=>{
// this.unbindEvent();
this.triger("stop");
this.mot.pow=1;
},3000)
}
on(ev,callback){
callback = callback||(function(){});
let fn = this.handEvent.find(arg=>arg.event);
if(!fn){
this.handEvent.push({event:ev,callback})
}
return this;
}
start(){
if(this.check==0){
this.bindEvent();
}
}
stop(){
this.check=0;
this.unbindEvent();
return this;
//this.handEvent=[];//记录
}
triger(ev){
let fn = this.handEvent.find(arg=>arg.ev);
switch(ev){
case "start":
case "action":
case "stop":console.log(ev);break;
}
if(fn){
fn.callback(this.mot.pow,this);
}
}
bindSelfEvent=()=>{
}
bindEvent(){
//监控摇一摇
window.addEventListener("devicemotion", this.EVENT_Deviceorientation, false);
}
unbindEvent(){
Object.assign(this.mot,{ pow:1});
window.removeEventListener("devicemotion",this.EVENT_Deviceorientation);
}
EVENT_Deviceorientation=(eventData)=>{
var acceleration = eventData.accelerationIncludingGravity;
var curTime = new Date().getTime();
if ((curTime - this.mot.last_update) > 300) {
var diffTime = curTime - this.mot.last_update;
this.mot.last_update = curTime;
this.mot.x = acceleration.x;
this.mot.y = acceleration.y;
this.mot.z = acceleration.z;
var speed = Math.abs(this.mot.x + this.mot.y + this.mot.z - this.mot.last_x - this.mot.last_y - this.mot.last_z) / diffTime * 10000;
if (speed > this.mot.step) {
if(this.mot.pow==1){
this.triger("start");
}
this.triger("action");
this.mot.pow+=1;
this.setTime();
}
this.mot.last_x = this.mot.x;
this.mot.last_y = this.mot.y;
this.mot.last_z = this.mot.z;
}
}
}
export default shake;
网友评论