HTML5手勢(shì)檢測(cè)原理和實(shí)現(xiàn)

2016-10-24    藍(lán)藍(lán)設(shè)計(jì)的小編

如果您想訂閱本博客內(nèi)容,每天自動(dòng)發(fā)到您的郵箱中, 請(qǐng)點(diǎn)這里

前言

隨著 Hybrid 應(yīng)用的豐富,HTML5 工程師們已經(jīng)不滿(mǎn)足于把桌面端體驗(yàn)簡(jiǎn)單移植到移動(dòng)端,他們覬覦移動(dòng)原生應(yīng)用人性化的操作體驗(yàn),特別是原生應(yīng)用與生俱來(lái)的豐富的手勢(shì)系統(tǒng)。HTML5 沒(méi)有提供開(kāi)箱即用的手勢(shì)系統(tǒng),但是提供了更底層一些的對(duì) touch 事件的監(jiān)聽(tīng)?;诖?,我們可以做出自己的手勢(shì)庫(kù)。

手勢(shì)

常用的 HTML5 手勢(shì)可以分為兩類(lèi),單點(diǎn)手勢(shì)和兩點(diǎn)手勢(shì)。單點(diǎn)手勢(shì)有 tap(單擊),double tap(雙擊),long tap(長(zhǎng)按),swipe(揮),move(移動(dòng))。兩點(diǎn)手勢(shì)有 pinch(縮放),rotate(旋轉(zhuǎn))。

接下來(lái)我們實(shí)現(xiàn)一個(gè)檢測(cè)這些手勢(shì)的 javaScript 庫(kù),并利用這個(gè)手勢(shì)庫(kù)做出炫酷的交互效果。

1.jpg

移動(dòng)

關(guān)于移動(dòng)手勢(shì)檢測(cè)我們這里不再贅述。總結(jié)一下就是在每次touchmove事件發(fā)生時(shí),把兩個(gè)位移點(diǎn)之間的坐標(biāo)位置相減,就可以了。

單擊(tap)

手勢(shì)檢測(cè)的關(guān)鍵是用 touchstart,touchmove,touchend 三個(gè)事件對(duì)手勢(shì)進(jìn)行分解。

那么怎么分解單擊事件呢?

  1. 在 touchstart 發(fā)生時(shí)進(jìn)入單擊檢測(cè),只有一個(gè)接觸點(diǎn)。因?yàn)閱螕羰录拗茷橐粋€(gè)手指的動(dòng)作。
  2. 沒(méi)有發(fā)生 touchmove 事件或者 touchmove 在一個(gè)很小的范圍(如下圖)。限制 touchmove 在一個(gè)很小范圍,是為了給用戶(hù)一定的冗余空間,因?yàn)椴荒鼙WC用戶(hù)手指在接觸屏幕的時(shí)候不發(fā)生輕微的位移。

2.jpg

 

3.touchend 發(fā)生在 touchstart后的很短時(shí)間內(nèi)(如下圖)。這個(gè)時(shí)間段的閾值是毫秒級(jí),用來(lái)限制手指和屏幕接觸的時(shí)間。因?yàn)閱螕羰录拈_(kāi)始到結(jié)束是很快的。

3.jpg

 

有了上面的流程,就可以開(kāi)始實(shí)現(xiàn) tap 事件監(jiān)測(cè)了。

_getTime() { return new Date().getTime(); 

}

_onTouchStart(e) { //記錄touch開(kāi)始的位置 this.startX = e.touches[0].pageX; this.startY = e.touches[0].pageY; if(e.touches.length > 1) { //多點(diǎn)監(jiān)測(cè) ...

    }else { //記錄touch開(kāi)始的時(shí)間 this.startTime = this._getTime();

    }

 }

_onTouchMove(e) {

  ... //記錄手指移動(dòng)的位置 this.moveX = e.touches[0].pageX; this.moveY = e.touches[0].pageY;

  ...

}

_onTouchEnd(e) { let timestamp = this._getTime(); if(this.moveX !== null && Math.abs(this.moveX - this.startX) > 10 || this.moveY !== null && Math.abs(this.moveY - this.startY) > 10) {

      ...

  }else { //手指移動(dòng)的位移要小于10像素并且手指和屏幕的接觸時(shí)間要短語(yǔ)500毫秒 if(timestamp - this.startTime < 500) { this._emitEvent('onTap')

    }

  }

}

雙擊(double tap)

和單擊一樣,雙擊事件也需要我們對(duì)手勢(shì)進(jìn)行量化分解。

  1. 雙擊事件是一個(gè)手指的行為。所以在 touchstart 時(shí),我們要判斷此時(shí)屏幕有幾個(gè)接觸點(diǎn)。
  2. 雙擊事件中包含兩次獨(dú)立的單擊行為。理想情況下,這兩次點(diǎn)擊應(yīng)該落在屏幕上的同一個(gè)點(diǎn)上。為了給用戶(hù)一定的冗余空間,將兩次點(diǎn)擊的坐標(biāo)點(diǎn)距離限制在10個(gè)像素以?xún)?nèi)。

4.jpg

 

雙擊事件本質(zhì)是兩次快速的單擊。也即是說(shuō),兩次點(diǎn)擊的間隔時(shí)間很短。通過(guò)一定的測(cè)試量化后,我們把兩次單擊的時(shí)間間隔設(shè)為300毫秒。
5.jpg

注意雙擊事件中我們檢測(cè)了相鄰兩個(gè) touchstart 事件的位移和時(shí)間間隔。

_onTouchStart(e) { if(e.touches.length > 1) {

  ...

  } else { if(this.previousTouchPoint) { //兩次相鄰的touchstart之間距離要小于10,同時(shí)時(shí)間間隔小于300ms if( Math.abs(this.startX -this.previousTouchPoint.startX) < 10 && Math.abs(this.startY - this.previousTouchPoint.startY) < 10 && Math.abs(this.startTime - this.previousTouchTime) < 300) { this._emitEvent('onDoubleTap');

          }

    } //保存上一次touchstart的時(shí)間和位置信息 this.previousTouchTime = this.startTime; this.previousTouchPoint = {

        startX : this.startX,

        startY : this.startY

     };

  }

}

長(zhǎng)按(long press)

長(zhǎng)按應(yīng)該是最容易分解的手勢(shì)。我們可以這樣分解:在 touchstart 發(fā)生后的很長(zhǎng)一段時(shí)間內(nèi),如果沒(méi)有發(fā)生 touchmove 或者 touchend 事件,那么就觸發(fā)長(zhǎng)按手勢(shì)。

  1. 長(zhǎng)按是一個(gè)手指的行為,需要檢測(cè)屏幕上是否只有一個(gè)接觸點(diǎn)。
  2. 如果手指在空間上發(fā)生了移動(dòng),那么長(zhǎng)按事件取消。
  3. 如果手指在屏幕上停留的時(shí)間超過(guò)800ms,那么觸發(fā)長(zhǎng)按手勢(shì)。
  4. 如果手指在屏幕上停留的時(shí)間小于800ms,也即 touchend 在 touchstart 發(fā)生后的800ms內(nèi)觸發(fā),那么長(zhǎng)按事件取消。


6.jpg

 

_onTouchStart(e) {

  clearTimeout(this.longPressTimeout); if(e.touches.length > 1) {

  }else { this.longPressTimeout = setTimeout(()=>{ this._emitEvent('onLongPress');

    });

  }

}

_onTouchMove(e) {

  ...

  clearTimeout(this.longPressTimeout);

  ...

}

_onTouchEnd(e) {

  ...

  clearTimeout(this.longPressTimeout);

  ...

}

縮放(pinch)

縮放是一個(gè)非常有趣的手勢(shì),還記得第一代iPhone雙指縮放圖片給你帶來(lái)的震撼嗎?雖然如此,縮放手勢(shì)的檢測(cè)卻相對(duì)簡(jiǎn)單。

  1. 縮放是兩個(gè)手指的行為,需要檢測(cè)屏幕上是否有兩個(gè)接觸點(diǎn)。
  2. 縮放比例的量化,是通過(guò)兩次縮放行為之間的距離的比值得到,如下圖。
    7.jpg

所以縮放的核心是獲取兩個(gè)接觸點(diǎn)之間的直線(xiàn)距離。

//勾股定理 _getDistance(xLen,yLen) { return Math.sqrt(xLen * xLen + yLen * yLen);
  }

這里的xLen是兩個(gè)接觸點(diǎn)x坐標(biāo)差的絕對(duì)值,yLen相應(yīng)的就是y坐標(biāo)差的絕對(duì)值。

_onTouchStart(e) { if(e.touches.length > 1) { let point1 = e.touches[0]; let point2 = e.touches[1]; let xLen = Math.abs(point2.pageX - point1.pageX); let yLen = Math.abs(point2.pageY - point1.pageY); this.touchDistance = this._getDistance(xLen, yLen);

  } else {

    ...

  }

}

在_onTouchStart函數(shù)中獲取并且保存 touchstart 發(fā)生時(shí)兩個(gè)接觸點(diǎn)之間的距離。

_onTouchMove(e) { if(e.touches.length > 1) { let xLen = Math.abs(e.touches[0].pageX - e.touches[1].pageX); let yLen = Math.abs(e.touches[1].pageY - e.touches[1].pageY); let touchDistance = this._getDistance(xLen,yLen); if(this.touchDistance) { let pinchScale = touchDistance / this.touchDistance; this._emitEvent('onPinch',{scale:pinchScale - this.previousPinchScale}); this.previousPinchScale = pinchScale;

      }

  }else {

    ...

  }

}

旋轉(zhuǎn)(rotate)

旋轉(zhuǎn)手勢(shì)需要檢測(cè)兩個(gè)比較重要的值,一是旋轉(zhuǎn)的角度,二是旋轉(zhuǎn)的方向(順時(shí)針或逆時(shí)針)。

其中旋轉(zhuǎn)角度和方向的計(jì)算需要通過(guò)向量的計(jì)算來(lái)獲取,本文不再展開(kāi)。

8.jpg

 

首先,需要獲取向量的旋轉(zhuǎn)方向和角度。

//這兩個(gè)方法屬于向量計(jì)算,具體原理請(qǐng)閱讀本文最后的參考文獻(xiàn) _getRotateDirection(vector1,vector2) { return vector1.x * vector2.y - vector2.x * vector1.y;

  }  

  _getRotateAngle(vector1,vector2) { let direction = this._getRotateDirection(vector1,vector2);

    direction = direction > 0 ? -1 : 1; let len1 = this._getDistance(vector1.x,vector1.y); let len2 = this._getDistance(vector2.x,vector2.y); let mr = len1 * len2; if(mr === 0) return 0; let dot = vector1.x * vector2.x + vector1.y * vector2.y; let r = dot / mr; if(r > 1) r = 1; if(r < -1) r = -1; return Math.acos(r) * direction * 180 / Math.PI;

  }

然后,我們?cè)谑种赴l(fā)生移動(dòng)時(shí),調(diào)用獲取旋轉(zhuǎn)方向和角度的方法。

_onTouchStart(e) {

  ... if(e.touches.length > 1) { this.touchVector = {

       x: point2.pageX - this.startX,

       y: point2.pageY - this.startY

     };

  }

  ...

}

_onTouchMove(e) {

  ... if(this.touchVector) { let vector = {

          x: e.touches[1].pageX - e.touches[0].pageX,

          y: e.touches[1].pageY - e.touches[0].pageY

        }; let angle = this._getRotateAngle(vector,this.touchVector); this._emitEvent('onRotate',{

          angle

        }); this.touchVector.x = vector.x; this.touchVector.y = vector.y;

      }

  ...

}

實(shí)戰(zhàn)

好了,我們的手勢(shì)系統(tǒng)到這里就完成了。接下來(lái)要在實(shí)戰(zhàn)中檢驗(yàn)這套系統(tǒng)是否可靠,做一個(gè)簡(jiǎn)單的圖片瀏覽器,支持圖片縮放,旋轉(zhuǎn),移動(dòng),長(zhǎng)按。

首先,做好DOM規(guī)劃,和“之前”一樣,我們的事件監(jiān)聽(tīng)機(jī)制并不直接作用在圖片上,而是作用在圖片的父元素上。

9.jpg 

然后,可以開(kāi)始使用上面的手勢(shì)檢測(cè)系統(tǒng)了。

render() { return ( <Gestures onPinch={this.onPinch} onMove={this.onMove} onRotate={this.onRotate} onDoubleTap={this.onDoubleTap} onLongPress={this.onLongPress}> <div className="wrapper" > ![](http://upload-images.jianshu.io/upload_images/2362670-f8b44d4b9101e8d6.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) </div> </Gestures> );

  }

由于我們的手勢(shì)系統(tǒng)檢測(cè)的增量,因此不能直接把增量應(yīng)用在對(duì)象上,而是需要把這些增量累加。以旋轉(zhuǎn)為例:

onRotate(event) { //對(duì)增量進(jìn)行累加 this.angle += event.angle this.setState({

      angle:this.angle

    });

  }

至此,我們的手勢(shì)檢測(cè)就完成了。

 

 藍(lán)藍(lán)設(shè)計(jì)www.bouu.cn )是一家專(zhuān)注而深入的界面設(shè)計(jì)公司,為期望卓越的國(guó)內(nèi)外企業(yè)提供卓越的UI界面設(shè)計(jì)BS界面設(shè)計(jì) 、 cs界面設(shè)計(jì) 、 ipad界面設(shè)計(jì) 、 包裝設(shè)計(jì)  圖標(biāo)定制 、 用戶(hù)體驗(yàn) 、交互設(shè)計(jì)、 網(wǎng)站建設(shè) 、平面設(shè)計(jì)服務(wù) 

 

分享本文至:

日歷

鏈接

個(gè)人資料

存檔