美文网首页
javascript 检测手机设备重力方向

javascript 检测手机设备重力方向

作者: EdmundChen | 来源:发表于2017-08-10 14:54 被阅读61次

    两种javascript事件负责处理设备方向信息

    1. DeviceOrientationEvent,它会在加速度传感器检测到设备在方向上产生变化时触发。通过处理该事件传来的数据信息,使针对由于用户移动设备引起旋转和仰角变化的行为设计交互响应成为可能
    2. DeviceMotionEvent,它会在加速度发生改变时触发。跟DeviceOrientationEvent不同,DeviceMotionEvent监听的是加速度的变化而不是方向。传感器通常都具有监听DeviceMotionEvent的能力,包括笔记本用于保护移动存储设备的传感器。而能监听DeviceOrientationEvent事件的传感器更多出现在移动设备中

    处理方向(orientation)事件

    要接收设备方向变化信息,你只需要监听deviceorientation事件:

    相关值解释

    关于每一个轴的记录值表示的是相对于标准的坐标系,设备在某一个给定轴上的旋转量。Orientation and motion data explained 这篇文章有更详细的描述,下面是对这篇文章的总结。

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

    这个例子会成功运行在支持检测自己方向的设备中的支持deviceorientation 事件的浏览器中。

    想象一下花园(garden)中的一个球(ball):

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

    花园只有200px宽(很小对吧),球在中央:

    .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%;
    }
    

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

    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 + "\n";
      output.innerHTML += "gamma: " + y + "\n";
    
      // 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);
    

    相关文章

      网友评论

          本文标题:javascript 检测手机设备重力方向

          本文链接:https://www.haomeiwen.com/subject/mbyhrxtx.html