移动设备的晃动DeviceOrientationEvent

处理方向事件(要接收设备方向变化信息,你只需要注册监听deviceorientation事件)

window.addEventListener("deviceorientation", handleOrientation, true);

注册完事件监听处理函数后(对应这个例子中的handleOrientation),监听函数会定期地接收到最新的设备方向数据。

方向事件对象中包含四个值:

DeviceOrientationEvent.absolute
DeviceOrientationEvent.alpha
DeviceOrientationEvent.beta
DeviceOrientationEvent.gamma

关于每一个轴的记录值表示的是相对于标准的坐标系,设备在某一个给定轴上的旋转量。

Orientation and motion data explained 这篇文章有更详细的描述,下面是对这篇文章的总结。

DeviceOrientationEvent.alpha 表示设备沿z轴上的旋转角度,范围为0~360。
DeviceOrientationEvent.beta 表示设备在x轴上的旋转角度,范围为-180~180。它描述的是设备由前向后旋转的情况。
DeviceOrientationEvent.gamma 表示设备在y轴上的旋转角度,范围为-90~90。它描述的是设备由左向右旋转的情况。

例子:

<div class="garden">
  <div class="ball"></div>
</div>

<pre class="output"></pre>

css:

.garden {
  position: relative;
  width : 200px;
  height: 200px;
  border: 5px solid #CCC;
  border-radius: 10px;
}

.ball {
  position: absolute;
  top   : 90px;
  left  : 90px;
  width : 20px;
  height: 20px;
  background: green;
  border-radius: 100%;
}

js:现在,如果我们移动设备,球将随之移动:

var ball   = document.querySelector('.ball');
var garden = document.querySelector('.garden');
var output = document.querySelector('.output');

var maxX = garden.clientWidth  - ball.clientWidth;
var maxY = garden.clientHeight - ball.clientHeight;

function handleOrientation(event) {
  var x = event.beta;  // In degree in the range [-180,180]
  var y = event.gamma; // In degree in the range [-90,90]

  output.innerHTML  = "beta : " + x + "
";
  output.innerHTML += "gamma: " + y + "
";

  // Because we don't want to have the device upside down
  // We constrain the x value to the range [-90,90]
  if (x >  90) { x =  90};
  if (x < -90) { x = -90};

  // To make computation easier we shift the range of 
  // x and y to [0,180]
  x += 90;
  y += 90;

  // 10 is half the size of the ball
  // It center the positioning point to the center of the ball
  ball.style.top  = (maxX*x/180 - 10) + "px";
  ball.style.left = (maxY*y/180 - 10) + "px";
}

window.addEventListener('deviceorientation', handleOrientation);
原文地址:https://www.cnblogs.com/mychz/p/9548134.html