Nonsense not to say more, directly to everyone to paste the code, the specific code as follows:
var shaker = function (f) {//Shake Shake: Detect 3 times shaking calculate once shake, shake call processing function, no longer detect shake//F Shake callback this.callback = f; this.status = 0;//0:
Listening not started 1: listening start this.speed = 15;
THIS.LASTX = this.lasty = This.lastz = 0; This.num = 0; Detection Trigger Number this.minnum = 3; Minimum detection trigger number This.beginsecond = 0; Number of seconds to start detection this.maxsecond = 3;
Maximum interval of seconds This.handlerwrap = function () {}; } Shaker.prototype.listen = function () {//listening 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 for if (this.status = = 1) {if (window).
Devicemotionevent) {window.removeeventlistener (' devicemotion ', this.handlerwrap);} this.status = 0;
This.num = 0;
} Shaker.prototype.reset = function () {//Reset detection if (this.status = = 1) {this.num = 0;}} Shaker.prototype.handler = function (event) {//Sensor events Handling 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 () {/* The callback/* after the Shake/});
S.listen ();
Well, this article described to you here, the follow-up will continue to update, I hope this article to share the Web site detection shake The example code of the relevant knowledge to help everyone.