over 3 years ago

我們可以透過此API來存取裝置的acceleration, rotation rateorientation
但要注意的是,目前各家browser的支援度與計算方式都不太相同

DeviceMotion & DeviceMotionEvent

https://developer.mozilla.org/en-US/docs/Web/Events/devicemotion
https://developer.mozilla.org/en-US/docs/Web/API/DeviceMotionEvent

DeviceMotion.acceleration

回傳X,Y,Z三軸的加速度(m/s^2)

DeviceMotion.accelerationIncludingGravity

回傳考慮重力的X,Y,Z三軸的加速度(m/s^2)
將重力的資訊考慮進去的加速度結果,比如說一支平放在水平面上的手機
透過acceleration所得到的z會等於0
透過accelerationIncludingGravity所得到的z會大約等於重力加速度-9.8 (負號表示方向相反)
注意的是,若裝置沒有重力感測器,則回傳的結果會與acceleration相同

DeviceMotion.rotationRate

回傳 alpha, beta, gamma (degree per second)
rotationRate是計算各軸線的旋轉率,若是裝置無法提供此訊息,將會回傳 null
alpha 代表與螢幕垂直的軸線的旋轉率
beta 代表與螢幕平面 左->右 軸線的旋轉率
gamma 代表與螢幕平面 下->上 軸線的旋轉率

DeviceMotion.interval

回傳頻率的倒數,也就是每次獲取data的時間t (millisecond)

DeviceMotionEvent & Example

if (window.DeviceMotionEvent) {
    // Add listener

    window.addEventListener('devicemotion', deviceMotionHandler, false);
} else {
    console.log('DeviceMotionEvent not support');
}
function deviceMotionHandler(event)
{
  // Get the data

  var accel_X = event.acceleration.x;
  var accel_Y = event.acceleration.y;
  var accel_Z = event.acceleration.z;
  var accel_inc_gravity_X = event.accelerationIncludingGravity.x;
  var accel_inc_gravity_Y = event.accelerationIncludingGravity.y;
  var accel_inc_gravity_Z = event.accelerationIncludingGravity.z;
  var alpha = event.rotationRate.alpha;
  var beta = event.rotationRate.beta;
  var gamma = event.rotationRate.gamma;
  var timeInterval = event.interval;
}

DeviceOrientation & DeviceOrientationEvent

https://developer.mozilla.org/en-US/docs/Web/Events/deviceorientation
https://developer.mozilla.org/en-US/docs/Web/API/DeviceOrientationEvent

DeviceOrientaion.absolute

回傳 true/false
若是true,代表採用相對地球的絕對角度; 若是false,代表採用相對的角度

DeviceOrientaion.alpha

alpha代表Z軸的旋轉量 0 <= alpha <= 360 度

DeviceOrientaion.beta

beta代表X軸的旋轉量,裝置的前後動向(front-to-back) -180 <= beta <= 180 度

DeviceOrientaion.gamma

gamma代表Y軸的選轉量,裝置的左右動向(side-to-side) -90 <= gamma <= 90 度

DeviceOrientaion & Example

if (window.DeviceOrientationEvent){
    // Add listener

    window.addEventListener("deviceorientation", deviceOrientationHandler, false);
}else{
    $('#showMessage2').html("NOT support");
    console.log("DeviceOrientationEvent not support");
}
function deviceOrientationHandler(event)
{
  // Get data

  var alpha = event.alpha;
  var beta = event.beta;
  var gamma = event.gamma;
}
← Firebase 介紹 (1) ReactJS Note (1) - Props and Data hooking →
 
comments powered by Disqus