查找设备是否向左或向右倾斜
Find if device is tilted left or right
我想了解设备在横向模式下是否向左、向右或完全不倾斜。示例:
完全没有:
左:
右:
我查看了 deviceorientation
API,但没有找到明确的方法来找到 none,向左或向右。如果 phone 仅稍微倾斜,我更愿意将其视为 none。如果我能得到一个旋转数字,如果向左为正,向右为负,如果 none 为 0,那就太棒了,但这不是必需的。我还想要一个尽可能支持浏览器的答案。
DeviceOrientation Eventdraft 的“4.1 设备定位事件”部分说
Thus the angles alpha, beta and gamma form a set of intrinsic Tait-Bryan angles of type Z-X'-Y''.
AFAIU,你想要的是将其转换为 Z-X'-Z'' instrinsic Euler angels and get the angel that represents the last rotation. Well, let's dust off 3D triganometric skills and with help from quite useful table in the Wikipedia 我们可以看到
spin = atan2(cos(beta)*sin(gamma), sin(beta))
或者如果我们将它放入一些 JS 代码中
window.addEventListener("deviceorientation", handleOrientation, true);
function handleOrientation(event) {
// those angles are in degrees
var alpha = event.alpha;
var beta = event.beta;
var gamma = event.gamma;
// JS math works in radians
var betaR = beta / 180 * Math.PI;
var gammaR = gamma / 180 * Math.PI;
var spinR = Math.atan2(Math.cos(betaR) * Math.sin(gammaR), Math.sin(betaR));
// convert back to degrees
var spin = spinR * 180 / Math.PI;
}
请注意,当设备处于自然纵向时,这样计算的 spin
是 0
。您的风景示例对应 -90
度。
还要注意 Orientation and motion data explained MDN 页面说
Warning: Currently, Firefox and Chrome do not handle these coordinates the same way. Take heed when using them.
我只在 Chrome 中的 iOS 上测试了我的代码。您可以在 https://plnkr.co/edit/78IAUlbkQZMmogdlxGAH?p=preview 观看现场演示。请注意,您需要单击预览区域右上角的图标 "Launch the preview in a separate window",否则它将不起作用,因为至少在iOS.
我想了解设备在横向模式下是否向左、向右或完全不倾斜。示例:
完全没有:
左:
右:
我查看了 deviceorientation
API,但没有找到明确的方法来找到 none,向左或向右。如果 phone 仅稍微倾斜,我更愿意将其视为 none。如果我能得到一个旋转数字,如果向左为正,向右为负,如果 none 为 0,那就太棒了,但这不是必需的。我还想要一个尽可能支持浏览器的答案。
DeviceOrientation Eventdraft 的“4.1 设备定位事件”部分说
Thus the angles alpha, beta and gamma form a set of intrinsic Tait-Bryan angles of type Z-X'-Y''.
AFAIU,你想要的是将其转换为 Z-X'-Z'' instrinsic Euler angels and get the angel that represents the last rotation. Well, let's dust off 3D triganometric skills and with help from quite useful table in the Wikipedia 我们可以看到
spin = atan2(cos(beta)*sin(gamma), sin(beta))
或者如果我们将它放入一些 JS 代码中
window.addEventListener("deviceorientation", handleOrientation, true);
function handleOrientation(event) {
// those angles are in degrees
var alpha = event.alpha;
var beta = event.beta;
var gamma = event.gamma;
// JS math works in radians
var betaR = beta / 180 * Math.PI;
var gammaR = gamma / 180 * Math.PI;
var spinR = Math.atan2(Math.cos(betaR) * Math.sin(gammaR), Math.sin(betaR));
// convert back to degrees
var spin = spinR * 180 / Math.PI;
}
请注意,当设备处于自然纵向时,这样计算的 spin
是 0
。您的风景示例对应 -90
度。
还要注意 Orientation and motion data explained MDN 页面说
Warning: Currently, Firefox and Chrome do not handle these coordinates the same way. Take heed when using them.
我只在 Chrome 中的 iOS 上测试了我的代码。您可以在 https://plnkr.co/edit/78IAUlbkQZMmogdlxGAH?p=preview 观看现场演示。请注意,您需要单击预览区域右上角的图标 "Launch the preview in a separate window",否则它将不起作用,因为至少在iOS.