我创建了the following widget (see demo here)来模仿chrome开发人员标签上的传感器标签:
我的代码侦听设备的定向事件,并尝试将值转换为适合css转换比例的方式,
let phone = document.querySelector(".phone");
window.addEventListener('deviceorientation', (event) => {
phone.style.transform =
"rotateY(" + ( event.alpha) + "deg) "
+
"rotateX(" + (90 - event.beta) + "deg) "
+
"rotateZ(" + (event.gamma ) + "deg)";
})
但是,如果我对这些值玩得足够多,则我的小部件和chrome小部件将不同步。显然,我的计算是错误的,我想念什么?
要测试我的代码,只需转到demo,打开“开发工具”的“传感器”标签并使用小部件。
任何帮助将不胜感激。
更新: 要进入“传感器”选项卡:打开dev工具,按Esc,在第二个面板上,单击左侧的3点并选择传感器。
更新:
有问题的值的示例是:
alpha:-77.6163
beta:-173.4458
伽玛:-40.4889
答案 0 :(得分:2)
在铬和铬中就是这样:
最重要的部分是,当我们应用gamma
角度变换时,该轴已经通过先前的beta
角度变换旋转了。因此,我们需要将伽马旋转角不应用于(0, 0, 1)
轴,而是应用于考虑β角的变换轴。
来源:
function degreesToRadians (deg) {
return deg * Math.PI / 180;
}
class EulerAngles {
constructor(alpha, beta, gamma) {
this.alpha = alpha;
this.beta = beta;
this.gamma = gamma;
}
toRotate3DString() {
const gammaAxisY = -Math.sin(degreesToRadians(this.beta));
const gammaAxisZ = Math.cos(degreesToRadians(this.beta));
const axis = {
alpha: [0, 1, 0],
beta: [-1, 0, 0],
gamma: [0, gammaAxisY, gammaAxisZ]
};
return (
"rotate3d(" +
axis.alpha.join(",") +
"," +
this.alpha +
"deg) " +
"rotate3d(" +
axis.beta.join(",") +
"," +
this.beta +
"deg) " +
"rotate3d(" +
axis.gamma.join(",") +
"," +
this.gamma +
"deg)"
);
}
}
function ready(fn) {
if (
document.attachEvent
? document.readyState === "complete"
: document.readyState !== "loading"
) {
fn();
} else {
document.addEventListener("DOMContentLoaded", fn);
}
}
ready(() => {
let phone = document.querySelector(".phone");
window.addEventListener("deviceorientation", event => {
console.log(event);
const eulerAngles = new EulerAngles(event.alpha, -90 + event.beta, event.gamma)
phone.style.transform = eulerAngles.toRotate3DString();
});
});