Shlomi Schwartz
Shlomi Schwartz

Reputation: 8913

Device orientation data transformed to css behaves strange when using a real device

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

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?

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

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

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.

Upvotes: 0

Views: 275

Answers (1)

Shlomi Schwartz
Shlomi Schwartz

Reputation: 8913

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

Upvotes: 1

Related Questions