DIV CSS 佈局教程網

網頁搖一搖檢測:DeviceMotionEvent 實作分享
編輯:關於JavaScript     

行動裝置的搖動偵測靠的是 DeviceMotionEvent,瀏覽器會持續回報裝置的加速度變化。下面這個 Shaker 類別把它封裝成好呼叫的形式:註冊後開始偵聽,搖動達標就觸發回呼,並且自動停止,避免連續觸發。

完整程式碼

var Shaker = function(f){
  // 搖一搖:偵測到 3 次搖動算一次搖一搖,
  // 搖動後呼叫處理函式,不再繼續偵測
  // f 為搖動後的回呼
  this.callback = f;

  this.status = 0;          // 0: 偵聽未開始  1: 偵聽中
  this.speed = 15;          // 單軸變化超過此值即視為一次搖動
  this.lastX = this.lastY = this.lastZ = 0;
  this.num = 0;             // 觸發次數計數
  this.minNum = 3;          // 最少需要幾次觸發
  this.beginSecond = 0;     // 開始偵測的秒數
  this.maxSecond = 3;       // 允許的最大間隔秒數
  this.handlerWrap = function(){};
};

Shaker.prototype.listen = function(){
  // 開始偵聽
  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(){
  // 停止偵聽
  if (this.status == 1) {
    if (window.DeviceMotionEvent) {
      window.removeEventListener('devicemotion', this.handlerWrap);
    }
    this.status = 0;
    this.num = 0;
  }
};

Shaker.prototype.reset = function(){
  // 重置計數
  if (this.status == 1) {
    this.num = 0;
  }
};

Shaker.prototype.handler = function(event){
  // 傳感器事件處理
  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();
    }
  }
};

使用方式

var s = new Shaker(function(){
  /* 搖動後的回呼 */
});
s.listen();

幾個設計上的考量

第一,為什麼要限時?如果只數「搖了幾次」,使用者持續晃動手機也會達標,加上 maxSecond 的三秒窗口,才比較接近人類認知的「搖一下」。

第二,為什麼用 accelerationIncludingGravity 而不是 acceleration?前者在一般瀏覽器中支援度較高,後者需要裝置具備無重力感測能力才有值。

第三,handlerWrap 存在的意義是為了能正確移除監聽器——必須傳入與註冊時相同的函式引用,否則 removeEventListener 不會生效,這也是為什麼要用閉包把 that 包住的緣故。

第四,DeviceMotionEvent 在部分瀏覽器(尤其 iOS Safari)需要使用者主動授權,且必須在 HTTPS 環境下才能取得感測資料,因此正式上線前記得處理不支援與被拒絕的降級方案,例如改提供點擊或拖曳操作。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved