Categories: Cordova 教程

Cordova 加速计

该插件也称为 设备运动 它用于在三维中跟踪设备运动。

步骤1 – 安装加速计插件

我们将使用 cordova-CLI 安装此插件。键入以下代码到命令提示符窗口。

C:UsersusernameDesktopCordovaProject>cordova plugin add cordova-plugin-device-motion

步骤2 – 添加按钮

接下来,我们需要做的是在 index.html 文件中添加两个按钮。一个用于获取当前加速度,另一个将监视加速度变化。

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

步骤3 – 添加事件监听器

让我们将按钮的事件监听器添加到 index.js 中的 onDeviceReady 函数。

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

步骤4 – 创建函数

我们将创建两个函数。第一个将用于获取当前加速度,第二个将观察加速度,并且每三秒通知一次。我们还添加了由 setTimeout 函数包装的 clearWatch ,以在指定时间范围后停止观看加速。frequency 参数用于每三秒触发一次回调函数。

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

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

   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 + 
 +
         Acceleration Y:  + acceleration.y + 
 +
         Acceleration Z:  + acceleration.z + 
 +
         Timestamp:       + acceleration.timestamp + 
);

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

   };

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

现在,如果我们按 GET ACCELERATION 按钮,我们将获得当前的加速度值。如果我们按WATCH ACCELERATION,警报将每三秒触发一次。在显示第三个警告后,将调用 clearWatch 函数,并且我们不会再收到任何警报,因为我们将超时设置为10000毫秒。

andy

前端小白,在Web176教程网这个平台跟大家一起学习,加油!

Share
Published by
andy

Recent Posts

在 Chrome 中删除、允许和管理 Cookie

您可以选择删除现有 Cooki…

5 小时 ago

自定义指令:聊聊vue中的自定义指令应用法则

今天我们来聊聊vue中的自定义…

1 周 ago

聊聊Vue中@click.stop和@click.prevent

一起来学下聊聊Vue中@cli…

2 周 ago

Nginx 基本操作:启动、停止、重启命令。

我们来学习Nginx基础操作:…

2 周 ago

Vue3:手动清理keep-alive组件缓存的方法

Vue3中手动清理keep-a…

3 周 ago

聊聊React和Vue组件更新的实现及区别

React 和 Vue 都是当…

4 周 ago