読者です 読者をやめる 読者になる 読者になる

Hope is a Dream. Dream is a Hope.

非公開ふぃふぃ工房ブログ

↓LINE登録はこちら↓

定期的につぶやいてます. 記事に興味を持って頂いたかたや、Line Botを使ってみたいかたは試しに登録どうぞ

友だち追加

JavaScriptでデバイスの傾斜を計算する方法

数値計算 Javascript WEB

調べてみた

iPhoneの加速度センサを使って本体の角度(Rad)を計算する。

window.addEventListener("devicemotion", function(evt){
  var xg = evt.accelerationIncludingGravity.x; // 横方向の傾斜
  var yg = evt.accelerationIncludingGravity.y; // 縦方向の傾斜
  var zg = evt.accelerationIncludingGravity.z; // 上下方向の傾斜
  var angle={};
  angle.y = Math.floor(Math.atan2(yg,zg)/Math.PI * 180);
  angle.x = Math.floor(Math.atan2(xg,zg)/Math.PI * 180);
  angle.z = Math.floor(Math.atan2(yg,xg)/Math.PI * 180);
  if(angle.x < 0){
    angle.x += 360;
  }
  if(angle.y < 0){
    angle.y += 360;
  }
  if(angle.z < 0){
    angle.z += 360;
  }
  document.getElementById("result").innerHTML = "角度x:"+angle.x+"<br>角度y:"+angle.y+"<br>角度z:"+angle.z;
}, true);

DeviceMotionEvent

DeviceMotionEvent

window.addEventListener('devicemotion', function(event) {
  console.log(event.acceleration.x + ' m/s2');
  console.log(event.acceleration.y + ' m/s2');
  console.log(event.acceleration.z + ' m/s2');
  console.log(event.accelerationIncludingGravity.x + ' m/s2');
  console.log(event.accelerationIncludingGravity.y + ' m/s2');
  console.log(event.accelerationIncludingGravity.z + ' m/s2');
  console.log(event.rotationRate.alpha + ' rad/s');
  console.log(event.rotationRate.beta + ' rad/s');
  console.log(event.rotationRate.gamma + ' rad/s');
  console.log(event.interval + ' rad/s');
});

acceleration

加速度

Summary

An object giving the acceleration of the device on the three axis X, Y and Z. Acceleration is expressed in m/s2.

var acceleration = instanceOfDeviceMotionEvent.acceleration;

accelerationIncudeGravity

重力加速度を含んだ加速度?

Summary

An object giving the acceleration of the device on the three axis X, Y and Z with the effect of gravity. Acceleration is expressed in m/s2.

Syntax

var acceleration = instanceOfDeviceMotionEvent.accelerationIncludingGravity;

rotationRate

Summary

An object giving the rate of change of the device's orientation on the three orientation axis alpha, beta and gamma. Rotation rate is express in degrees per seconds.

Syntax

var acceleration = instanceOfDeviceMotionEvent.acceleration;

interval

計測周波数?

Summary

An object giving the rate of change of the device's orientation on the three orientation axis alpha, beta and gamma. Rotation rate is express in degrees per seconds.

Syntax

var interval = instanceOfDeviceMotionEvent.interval;