• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Cordova 加速计

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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

步骤1 - 安装加速计插件

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

C:\Users\username\Desktop\CordovaProject>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 + '\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,警报将每三秒触发一次。在显示第三个警告后,将调用 clearWatch 函数,并且我们不会再收到任何警报,因为我们将超时设置为10000毫秒。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Cordova 设备方向发布时间:2022-02-02
下一篇:
Cordova 设备发布时间:2022-02-02
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap