使用真实设备时,转换为css的设备方向数据的行为很奇怪 [英] Device orientation data transformed to css behaves strange when using a real device

查看:75
本文介绍了使用真实设备时,转换为css的设备方向数据的行为很奇怪的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题仍在继续上一个:
我创建了一个模仿手机方向的CSS小部件( js小提琴).使用dev-tools传感器选项卡时,小部件可以完美运行,将事件数据转换为CSS rotation3d字符串,如下所示(answer by @ Andrey):

This question is in continue to a previous one:
I've created a CSS widget mimicking the phone orientation (js fiddle). When using the dev-tools sensors tab, the widget works perfectly, transforming the event data to a CSS rotate3d string like so (answer by@Andrey):

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)"
    );
  }
}

但是,如果我使用真实的设备(导航至js小提琴),则会出现奇怪的行为,尤其是在以纵向模式握住手机时.这是为什么?我该如何解决?

However, if I use a real device (navigating to the js fiddle), I get strange behaviors, especially when holding the phone in portrait mode. Why is that? how can I fix it?

更新:
阅读此答案后,我想我的问题是我正在使用Euler角度. 此视频很好地说明了这一点.

Update:
After reading this answer, I guess my problem is that I'm using Euler angles. This video explains it well.

但是,我仍在努力将设备方向数据(alpha,beta,gamma)转换为稳定的CSS转换.

However, I'm still struggling with converting the device orientation data (alpha, beta, gamma) to a stable CSS transformation.

我当时在考虑使用matrix3d转换,但是缺乏转换alpha,beta和amp;的数学知识.伽玛转换为4X4矩阵.

I was thinking of using matrix3d transform, but lack the mathematical knowledge of converting alpha, beta & gamma to a 4X4 matrix.

任何帮助将不胜感激.

Any help will be appreciated.

推荐答案

发现使用四元数是遇到该问题(Gimbel锁)时要走的路.我发现了一个出色的 npm库可以像这样处理数学:

Found out that using Quaternion is the way to go when encountering that problem (Gimbel lock). I've found an excellent npm library to handle the math like so:

var rad = Math.PI / 180;
window.addEventListener("deviceorientation", function(ev) {

  // Update the rotation object
  var q = Quaternion.fromEuler(ev.alpha * rad, ev.beta * rad, ev.gamma * rad, 'ZXY');

  // Set the CSS style to the element you want to rotate
  elm.style.transform = "matrix3d(" + q.conjugate().toMatrix4() + ")";

}, true);

这篇关于使用真实设备时,转换为css的设备方向数据的行为很奇怪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆