Share web page detection shake instance code

  • 2020-12-05 17:06:19
  • OfStack

Without further ado, I posted the code directly to you. The specific code is as follows:


var Shaker = function(f){
//  shake 1 shake :  detected 3 Time moved to calculate 1 Time shaking 1 shake ,  The handler is called after the shake ,  No longer detects shaking 
// f  A callback after shaking 
this.callback = f;
this.status = 0; // 0:  Interception not started  1:  Listen to start  
this.speed = 15;
this.lastX = this.lastY = this.lastZ = 0;
this.num = 0; //  Detection triggering times 
this.minNum = 3; //  Minimum number of detection triggers 
this.beginSecond = 0; //  Number of seconds to start detection 
this.maxSecond = 3; //  Maximum interval seconds 
this.handlerWrap = function(){};
}
Shaker.prototype.listen = function(){
//  Listen to shake 
var that = this;
if (this.status == 0 && window.DeviceMotionEvent) {
this.status = 1;
this.handlerWrap = function(event){
that.handler(event)
}
window.addEventListener('devicemotion', this.handlerWrap, false);
}
}
Shaker.prototype.release = function(){
//  Stop listening 
if(this.status == 1){
if (window.DeviceMotionEvent) {
window.removeEventListener('devicemotion', this.handlerWrap);
}
this.status = 0;
this.num = 0;
}
}
Shaker.prototype.reset = function(){
//  Reset the detection 
if(this.status == 1){
this.num = 0;
}
}
Shaker.prototype.handler = function(event){
//  Sensor event processing 
if(this.status == 1){
var acceleration =event.accelerationIncludingGravity;
var x = acceleration.x;
var y = acceleration.y;
var z = acceleration.z;
if( Math.abs(x-this.lastX) > this.speed || 
Math.abs(y-this.lastY) > this.speed || 
Math.abs(z-this.lastZ) > this.speed ) 
{
if(this.num == 0){
this.beginSecond = Date.parse(new Date()) / 1000
}
this.num += 1;
}
this.lastX = x;
this.lastY = y;
this.lastZ = z;
if(this.num >= this.minNum){
var now = Date.parse(new Date()) / 1000;
if(now - this.beginSecond <= this.maxSecond){
this.release();
if(this.callback){
this.callback();
}
}
this.reset();
}
}
}

Usage:


var s = new Shaker(function(){ /* A callback after shaking */ });
s.listen();

Well, this article introduced to you here, the follow-up will continue to update, I hope this article to share with you the web detection shake 1 shake example code related knowledge to help you.


Related articles: