如何从 Javascript 访问加速度计/陀螺仪数据?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4378435/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to access accelerometer/gyroscope data from Javascript?
提问by J?rn Schou-Rode
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?
这是怎么做的?我必须订阅window
对象上的某种事件吗?
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 isavailable 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.
注意:我实际上已经知道(部分)这个问题的答案,我将立即发布。我在这里张贴问题的原因,是为了让每个人都知道,加速度计数据是在Javascript中可用的(在某些设备上),并挑战社会关于这个问题发表新的研究结果。目前,似乎几乎没有这些功能的文档。
采纳答案by str
The way to do this in 2019+ is to use DeviceOrientation
API. This works in most modern browserson desktop and mobile.
在 2019+ 中做到这一点的方法是使用DeviceOrientation
API。这适用于桌面和移动设备上的大多数现代浏览器。
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 }
window.addEventListener("deviceorientation", handleOrientation, true);
注册您的事件侦听器(在本例中为一个名为 handleOrientation() 的 JavaScript 函数)后,您的侦听器函数会定期调用并使用更新的方向数据。
方向事件包含四个值:
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; // Do stuff with the new orientation data }
回答by J?rn Schou-Rode
There are currently three distinct events which may or may not be triggered when the client devices moves. Two of them are focused around orientationand the last on motion:
当前存在三个不同的事件,当客户端设备移动时可能会或可能不会触发这些事件。其中两个关注方向,最后一个关注运动:
ondeviceorientation
is known to work on the desktop version of Chrome, and most Apple laptops seems to have the hardware required for this to work. It also works on Mobile Safari on the iPhone 4 with iOS 4.2. In the event handler function, you can accessalpha
,beta
,gamma
values on the event data supplied as the only argument to the function.onmozorientation
is supported on Firefox 3.6 and newer. Again, this is known to work on most Apple laptops, but might work on Windows or Linux machines with accelerometer as well. In the event handler function, look forx
,y
,z
fields on the event data supplied as first argument.ondevicemotion
is known to work on iPhone 3GS + 4 and iPad (both with iOS 4.2), and provides data related to the current acceleration of the client device. The event data passed to the handler function hasacceleration
andaccelerationIncludingGravity
, which both have three fields for each axis:x
,y
,z
ondeviceorientation
已知可以在桌面版 Chrome 上运行,并且大多数 Apple 笔记本电脑似乎都具有运行所需的硬件。它也适用于装有 iOS 4.2 的 iPhone 4 上的 Mobile Safari。在事件处理函数中,您可以访问作为函数唯一参数提供的事件数据的alpha
,beta
,gamma
值。onmozorientation
Firefox 3.6 及更新版本支持。同样,众所周知,这适用于大多数 Apple 笔记本电脑,但也可能适用于带有加速度计的 Windows 或 Linux 机器。在事件处理函数中,在作为第一个参数提供的事件数据上查找x
,y
,z
字段。ondevicemotion
已知适用于 iPhone 3GS + 4 和 iPad(均使用 iOS 4.2),并提供与客户端设备当前加速相关的数据。传递给处理函数的事件数据有acceleration
和accelerationIncludingGravity
,每个轴都有三个字段:x
、y
、z
The "earthquake detecting" sample website uses a series of if
statements to figure out which event to attach to (in a somewhat prioritized order) and passes the data received to a common tilt
function:
“地震检测”示例网站使用一系列if
语句来确定要附加到哪个事件(以某种优先顺序)并将接收到的数据传递给一个通用tilt
函数:
if (window.DeviceOrientationEvent) {
window.addEventListener("deviceorientation", function () {
tilt([event.beta, event.gamma]);
}, true);
} else if (window.DeviceMotionEvent) {
window.addEventListener('devicemotion', function () {
tilt([event.acceleration.x * 2, event.acceleration.y * 2]);
}, true);
} else {
window.addEventListener("MozOrientation", function () {
tilt([orientation.x * 50, orientation.y * 50]);
}, true);
}
The constant factors 2 and 50 are used to "align" the readings from the two latter events with those from the first, but these are by no meansprecise representations. For this simple "toy" project it works just fine, but if you need to use the data for something slightly more serious, you will have to get familiar with the units of the values provided in the different events and treat them with respect :)
常数因子 2 和 50 用于将后两个事件的读数与第一个事件的读数“对齐”,但这绝不是精确的表示。对于这个简单的“玩具”项目,它工作得很好,但是如果您需要将数据用于更严重的事情,您将必须熟悉不同事件中提供的值的单位并尊重它们:)
回答by Infinite Internship
Can't add a comment to the excellent explanation in the other post but wanted to mention that a great documentation source can be found here.
无法在另一篇文章中对出色的解释添加评论,但想提一下可以在这里找到一个很好的文档来源。
It is enough to register an event function for accelerometer like so:
为加速度计注册一个事件函数就足够了,如下所示:
if(window.DeviceMotionEvent){
window.addEventListener("devicemotion", motion, false);
}else{
console.log("DeviceMotionEvent is not supported");
}
with the handler:
与处理程序:
function motion(event){
console.log("Accelerometer: "
+ event.accelerationIncludingGravity.x + ", "
+ event.accelerationIncludingGravity.y + ", "
+ event.accelerationIncludingGravity.z
);
}
And for magnetometer a following event handler has to be registered:
对于磁力计,必须注册以下事件处理程序:
if(window.DeviceOrientationEvent){
window.addEventListener("deviceorientation", orientation, false);
}else{
console.log("DeviceOrientationEvent is not supported");
}
with a handler:
带有处理程序:
function orientation(event){
console.log("Magnetometer: "
+ event.alpha + ", "
+ event.beta + ", "
+ event.gamma
);
}
There are also fields specified in the motion event for a gyroscope but that does not seem to be universally supported (e.g. it didn't work on a Samsung Galaxy Note).
在陀螺仪的运动事件中还指定了一些字段,但这似乎并未得到普遍支持(例如,它不适用于三星 Galaxy Note)。
There is a simple working code on GitHub
GitHub 上有一个简单的工作代码
回答by Luckylooke
Usefull fallback here: https://developer.mozilla.org/en-US/docs/Web/Events/MozOrientation
有用的回退:https: //developer.mozilla.org/en-US/docs/Web/Events/MozOrientation
function orientationhandler(evt){
// For FF3.6+
if (!evt.gamma && !evt.beta) {
evt.gamma = -(evt.x * (180 / Math.PI));
evt.beta = -(evt.y * (180 / Math.PI));
}
// use evt.gamma, evt.beta, and evt.alpha
// according to dev.w3.org/geo/api/spec-source-orientation
}
window.addEventListener('deviceorientation', orientationhandler, false);
window.addEventListener('MozOrientation', orientationhandler, false);