我最近发现一些网站似乎可以访问我笔记本电脑上的加速度计或陀螺仪,检测方向或运动的变化.
这是怎么做到的?我必须在 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 访问加速度计/陀螺仪数据?
发布评论