新年不是搞了個搖籤的功能嗎,彈幕效果我們前面講過了,今天來講說搖一搖效果html
完整 DEMO前端
html 5 提供了一些方法在移動端得到設備方向及運動(由於他是依賴傳感器硬件的,pc 沒有也不存在抱着臺式機跑來跑去場景)。傳感器包括陀螺儀、加速器和磁力儀(羅盤)。vue
能夠實現什麼效果?segmentfault
DeviceMotionEvent
在設備發生擺動、運動(手機瘋狂搖擺,搖一搖場景)時產生。數組
devicemotion
是用來監聽手機加速度變化的事件回調中能夠提供設備的加速度信息。
表示爲在設備上定義的座標系中的笛卡爾座標,提供了設備在座標系中的自轉速率。瀏覽器
對於一個豎屏擺放的設備來講,設備三個方向軸的位置爲:微信
有 4 個只讀屬性:屬性測試Demo,搖晃小球Demo(加速度)測試
m/s²
。重力加速度(包括重心引力)m/s²
。加速度(須要設備陀螺儀支持)°/s
(degrees per seconds) 。旋轉速度 DeviceOrientationEvent
加速度傳感器檢測到設備在方向上產生變化時觸發。
監聽設備方向(設備旋轉和仰角變化的行爲),提供設備的物理方向信息,表示爲一系列本地座標系的旋角。this
屬性有三個,用於描述設備方向:屬性測試,搖晃小球Demo(當前設備方向)spa
當手機禁止的時候你會發現他是不動的。拿起移動時就會發現回調開始調用。
devicemotion-demo 咱們可使用 devicemotion
直接來監聽設備的運動,當他超過特定的閾值,咱們就認爲在搖一搖。
接下來,咱們能夠搖起來了,能夠看到背景色會從綠色變爲黃色,而後也有觸發閾值的次數的統計。
window.addEventListener('devicemotion', (e) => { console.log(e) if(this.devicemotionReturn) return ; this.historyDevicemotion = JSON.parse(JSON.stringify(this.devicemotion)) this.devicemotion.accelerationIncludingGravity.x = e.accelerationIncludingGravity.x this.devicemotion.accelerationIncludingGravity.y = e.accelerationIncludingGravity.y this.devicemotion.accelerationIncludingGravity.z = e.accelerationIncludingGravity.z if(this.historyDevicemotion.accelerationIncludingGravity.x || this.historyDevicemotion.accelerationIncludingGravity.y || this.historyDevicemotion.accelerationIncludingGravity.z){ // 計算單一方向加速度的差值 var thresholdCount = Math.max( Math.abs(this.historyDevicemotion.accelerationIncludingGravity.x - e.accelerationIncludingGravity.x), Math.abs(this.historyDevicemotion.accelerationIncludingGravity.y - e.accelerationIncludingGravity.y), Math.abs(this.historyDevicemotion.accelerationIncludingGravity.z - e.accelerationIncludingGravity.z) ) // 閾值判斷 if(thresholdCount > 1) this.devicemotion.thresholdCount_1++; if(thresholdCount > 5) this.devicemotion.thresholdCount_5++; if(thresholdCount > 10) this.devicemotion.thresholdCount_10++; if(thresholdCount > 15) this.devicemotion.thresholdCount_15++; if(thresholdCount > 20) this.devicemotion.thresholdCount_20++; if(thresholdCount > 25) this.devicemotion.thresholdCount_25++; if(thresholdCount > 50) this.devicemotion.thresholdCount_50++; if(thresholdCount > 100) this.devicemotion.thresholdCount_100++; // 顏色變化邏輯 if(thresholdCount > 20) this.devicemotion.shakeValue = Math.min(255, this.devicemotion.shakeValue + 10) } })
deviceorientation
來監聽設備的方向變化,也是設置閾值,超過必定的幅度咱們就認爲在搖動手機。測試方法同上我就很少介紹了。測試地址 Navigator.vibrate()
可使設備(需硬件支持,手機通常都有響鈴並震動功能)產生有頻率(能夠傳入數組)的震動。
若設備不支持震動,該方法將無效。
若某震動方式已經在進行中(當該方法調用時),則前一個震動方式中止,新的取而代之。
若由於提供無效的參數使得沒法使設備震動,它將返回false,不然返回true。
若振動方案致使長時間的震動,它會被截斷:最大震動時長取決於每一個瀏覽器的具體實現。
navigator.vibrate(duration);
window.navigator.vibrate(200);
一個200ms的震動window.navigator.vibrate(0);
中止震動,能夠理解爲覆蓋,而後震動0mswindow.navigator.vibrate([100,30,100,30,100,200,200,30,200,30,200,200,100,30,100,30,100]);
有頻率的震動,奇數位爲震動時間,偶數位爲暫停時間。我下標按1開始的啊。聲音播放咱們就直接使用 audio 標籤實現便可,測試地址。複雜一點能夠看我以前寫的基於better-scroll 實現歌詞聯動功能。
歡迎你們關注個人公衆號。有疑問也能夠加個人微信前端交流羣。