Cordova 加速計

2018-12-28 15:23 更新

該插件也稱為 設備運動 。它用于在三維中跟蹤設備運動。

步驟1 - 安裝加速計插件

我們將使用 cordova-CLI 安裝此插件。鍵入以下代碼到命令提示符窗口。

C:\Users\username\Desktop\CordovaProject>cordova plugin add cordova-plugin-device-motion

步驟2 - 添加按鈕

接下來,我們需要做的是在 index.html 文件中添加兩個按鈕。一個用于獲取當前加速度,另一個將監(jiān)視加速度變化。

<button id = "getAcceleration">GET ACCELERATION</button>
<button id = "watchAcceleration">WATCH ACCELERATION</button>

步驟3 - 添加事件監(jiān)聽器

讓我們將按鈕的事件監(jiān)聽器添加到 index.js 中的 onDeviceReady 函數。

document.getElementById("getAcceleration").addEventListener("click", getAcceleration);
document.getElementById("watchAcceleration").addEventListener("click", watchAcceleration);

步驟4 - 創(chuàng)建函數

我們將創(chuàng)建兩個函數。第一個將用于獲取當前加速度,第二個將觀察加速度,并且每三秒通知一次。我們還添加了由 setTimeout 函數包裝的 clearWatch ,以在指定時間范圍后停止觀看加速。frequency 參數用于每三秒觸發(fā)一次回調函數。

function getAcceleration(){
   navigator.accelerometer.getCurrentAcceleration(accelerometerSuccess, accelerometerError);

   function accelerometerSuccess(acceleration) {
      alert('Acceleration X: ' + acceleration.x + '\n' +
         'Acceleration Y: ' + acceleration.y + '\n' +
         'Acceleration Z: ' + acceleration.z + '\n' +
         'Timestamp: '      + acceleration.timestamp + '\n');
   };

   function accelerometerError() {
      alert('onError!');
   };
	
}

function watchAcceleration(){
    
   var accelerometerOptions = {
      frequency: 3000
   }

   var watchID = navigator.accelerometer.watchAcceleration(accelerometerSuccess, accelerometerError, accelerometerOptions);

   function accelerometerSuccess(acceleration) {
      alert('Acceleration X: ' + acceleration.x + '\n' +
         'Acceleration Y: ' + acceleration.y + '\n' +
         'Acceleration Z: ' + acceleration.z + '\n' +
         'Timestamp: '      + acceleration.timestamp + '\n');

      setTimeout(function() {
         navigator.accelerometer.clearWatch(watchID);
      }, 10000);

   };

   function accelerometerError() {
      alert('onError!');
   };
	
}

現在,如果我們按 GET ACCELERATION 按鈕,我們將獲得當前的加速度值。如果我們按WATCH ACCELERATION,警報將每三秒觸發(fā)一次。在顯示第三個警告后,將調用 clearWatch 函數,并且我們不會再收到任何警報,因為我們將超時設置為10000毫秒。

Cordova Acceleration
以上內容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號