Your location:Tech News>News>Script>Sharing pages shake detecting code examples

Latest News

Sharing pages shake detecting code examples

Author:fsadmin

Views:

  var Shaker = function (f) {

  // Shake: 3 detects a shake shaker operator, call handler After shaking, shaking is no longer detected

  After shaking callback // f

  this.callback = f;

  this.status = 0; // 0: Not started listening 1: listening for an

  this.speed = 15;

  this.lastX = this.lastY = this.lastZ = 0;

  this.num = 0; // number of detection trigger

  this.minNum = 3; // number of times the minimum detection trigger

  this.beginSecond = 0; // start detection seconds

  this.maxSecond = 3; // Maximum number of seconds between

  this.handlerWrap = function () {};

  }

  Shaker.prototype.listen = function () {

  // listens 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 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 ();

  }

  }

  }

Recommend article

Relate article