JS-检测设备在一个轴(X,Y,Z)上旋转的角度是否超过阈值度

时间:2019-01-17 12:30:51

标签: javascript web mobile sensors

我编写了以下JS,以使用DeviceOrientationEvent收集每个轴的10个设备方向数据样本:

    function addValue(arr,val){
      arr.push(val);
      if(arr.length > 10){
        //FIFO
        arr.shift();
      }
    }

    function checkMovement(){
        //TODO: Implement
    }

    function init() {
      let bufferA = [];
      let bufferB = [];
      let bufferG = [];
      window.addEventListener('deviceorientation', function(event) {
        addValue(bufferA,event.alpha);
        addValue(bufferB,event.beta);
        addValue(bufferG,event.gamma);
        console.log("Alpha:",bufferA);
        console.log("Beta:",bufferB);
        console.log("Gamma:",bufferG);
      });
    }

代码的工作原理和输出如下:

Alpha: (10) [270.1843934731245, 270.46643145307615, 270.5777617085752, 270.60145073101677, 270.6375654707842, 270.8057436294502, 270.8996987403409, 270.9120469572076, 270.6252518476537, 270.47210923234405]
Beta:  (10) [0.1752652827241338, 0.18823422659229486, 0.17726753978482904, 0.15365567314664708, 0.17945207160964366, 0.24686323651604228, 0.29261776755456925, 0.3637458880746612, 0.48965131703567966, 0.5984471316186161]
Gamma: (10) [0.04652736183550441, 0.04224191500987182, 0.04815352937436751, 0.16853189576371583, 0.32057100908945746, 0.2699882416274315, 0.1328731445658815, -0.22660041993990893, -0.48360428677544554, -0.5723959136181673]
...

现在,我想创建一个函数,该函数在调用时将查看运动历史记录(在轴数组中收集),并将确定设备是否在其中一个轴上旋转了X度以上。

1 个答案:

答案 0 :(得分:1)

您能尝试一次吗?

var previousOrientation = window.orientation;
var checkOrientation = function(){
    if(window.orientation !== previousOrientation){
        previousOrientation = window.orientation;
        // orientation changed, do your magic here
    }
};

window.addEventListener("resize", checkOrientation, false);
window.addEventListener("orientationchange", checkOrientation, false);

// (optional) Android doesn't always fire orientationChange on 180 degree turns
setInterval(checkOrientation, 2000);