Device orientation sensor to CSS transform

折月煮酒 提交于 2019-12-10 22:41:45

问题


I've created the following widget (see demo here) to mimic the sensors tab on the chrome developer tab:



My code listens to the orientation event of the device and tries to convert the values to fit the css transform scale, like so:

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

However, if I play around enough with the values, my widget and the chrome widget get out of sync. Obviously, my calculations are wrong, what am I missing?

To test my code, just go to the demo open the dev tools sensors tab and play around with the widget.

Any help would be appreciated.

Update: to get to the sensors tab: Open dev tools, press Esc, on the second panel click the 3dots on the left and choose sensors.

Update: Example of problematic values are:
alpha: -77.6163
beta:-173.4458
gamma:-40.4889


回答1:


That is how it is done in chromium and chrome:

codepen

Essential part there is that when we apply gamma angle transformation, the axis is already rotated by previous beta angle transformation. So we need to apply gamma rotation angle not to (0, 0, 1) axis but to transformed axis which considers beta angle.

Source:

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


来源:https://stackoverflow.com/questions/56649018/device-orientation-sensor-to-css-transform

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!