如何从 Javascript 访问加速度计/陀螺仪数据?

编程入门 行业动态 更新时间:2024-10-27 08:33:21
本文介绍了如何从 Javascript 访问加速度计/陀螺仪数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我最近发现一些网站似乎可以访问我笔记本电脑上的加速度计或陀螺仪,检测方向或运动的变化.

这是怎么做到的?我必须在 window 对象上订阅某种事件吗?

已知可以在哪些设备(笔记本电脑、手机、平板电脑)上使用?

注意:我实际上已经知道(部分)这个问题的答案,我会马上发布.我在这里发布问题的原因是让其他人知道加速度计数据 在 Javascript 中可用(在某些设备上),并挑战社区发布有关该主题的新发现.目前,似乎几乎没有关于这些功能的文档.

解决方案

2019+ 的做法是使用 DeviceOrientation API.这适用于桌面和移动设备上的大多数现代浏览器.

window.addEventListener("deviceorientation", handleOrientation, true);

在注册您的事件侦听器(在本例中为 JavaScript名为 handleOrientation()) 的函数,您的侦听器函数定期调用更新的方向数据.

方向事件包含四个值:

  • DeviceOrientationEvent.absolute
  • DeviceOrientationEvent.alpha
  • DeviceOrientationEvent.beta
  • DeviceOrientationEvent.gamma

事件处理函数看起来像这样:

function handleOrientation(event) {var absolute = event.absolute;var alpha = event.alpha;var beta = event.beta;var gamma = event.gamma;//用新的方向数据做一些事情}

I have recently come across a few websites that seems to access the accelerometer or gyroscope on my laptop, detecting changes in orientation or movement.

How is this done? Must I subscribe to some kind of event on the window object?

On which devices (laptops, mobile phones, tablets) is this known to work?

NB: I actually already know (part of) the answer to this question, and I am going to post it right away. The reason that I am posting the question here, is to let everyone else know that accelerometer data is available in Javascript (on certain devices) and to challenge the community to post new findings on the subject. Currently, there seems to be almost no documentation of these features.

解决方案

The way to do this in 2019+ is to use DeviceOrientation API. This works in most modern browsers on desktop and mobile.

window.addEventListener("deviceorientation", handleOrientation, true);

After registering your event listener (in this case, a JavaScript function called handleOrientation()), your listener function periodically gets called with updated orientation data.

The orientation event contains four values:

  • DeviceOrientationEvent.absolute
  • DeviceOrientationEvent.alpha
  • DeviceOrientationEvent.beta
  • DeviceOrientationEvent.gamma

The event handler function can look something like this:

function handleOrientation(event) { var absolute = event.absolute; var alpha = event.alpha; var beta = event.beta; var gamma = event.gamma; // Do stuff with the new orientation data }

更多推荐

如何从 Javascript 访问加速度计/陀螺仪数据?

本文发布于:2023-10-08 02:07:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1471203.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:加速度计   陀螺仪   数据   Javascript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!