網頁檢測搖一搖

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(){ /*搖動後的回調*/ });this

    s.listen();prototype

相關文章
相關標籤/搜索