如何获取horizon线与javascript中设备的夹角?

How to get the angle between the horizon line and the device in javascript?

我想在我的网站上显示一杯水 page.I 希望当用户旋转他们的设备时,水应该自然地下降到 horizon 线。

window.addEventListener('deviceorientation', this.handleOrientation.bind(this));

handleOrientation(orientData) {
    var absolute = orientData.absolute;
    var alpha = orientData.alpha;
    var beta = orientData.beta;
    var gamma = orientData.gamma;
}

从上面的api,我可以得到那四个角度的信息。但我不知道如何获得从设备到 horizon 线的当前角度,以便我可以将我的水旋转到 horizon 线。

基于 the example from MDN and a bit of trigonometry 我能够想出下面的代码。我在 Android 上的 Chrome 上成功测试了这个,遗憾的是 Firefox 不会触发 deviceorientation 事件(即使 MDN 上的示例也不起作用)。

另一个注意事项是 屏幕 方向,即如果您的设备当前处于横向模式。旧 API (window.orientation) 在某些浏览器中不受支持,新 API (screen.orientation) 尚未完全实现并且行为不同。

var watercup = document.querySelector('#watercup');

function handleOrientation(event) {
  var x = event.beta;  // In degree in the range [-180,180], x, 'front to back'
  var y = event.gamma; // In degree in the range [-90,90], y, 'left to right'
  var z = event.alpha; // 0-360, z, compass orientation

  // coord 1: 0,0
  // coord 2: x,y
  // calculate the angle
  var rad = Math.atan2(y, x);
  var deg = rad * (180 / Math.PI);

  // take into account if phone is held sideways / in landscape mode
  var screenOrientation = screen.orientation || screen.mozOrientation || screen.msOrientation;
  // 90, -90, or 0
  var angle = screenOrientation.angle || window.orientation || 0; 
  
  deg = deg + angle; 

  watercup.innerHTML = Math.round(deg);
  watercup.style.transform = 'rotate('+ -deg +'deg)';
}

window.addEventListener('deviceorientation', handleOrientation);
#watercup {
  border:2px solid #aaa;
  width:100px;
  height:200px;
  background: linear-gradient(to bottom, white 20%, lightblue 20%, blue);
  margin: 20px auto;
}
<div id="watercup"></div>