他の投稿の優れた説明にコメントを追加することはできませんが、優れたドキュメント ソースがここにあることに言及したいと思います。
次のように加速度計のイベント関数を登録するだけで十分です。
if(window.DeviceMotionEvent){
window.addEventListener("devicemotion", motion, false);
}else{
console.log("DeviceMotionEvent is not supported");
}
ハンドラーで:
function motion(event){
console.log("Accelerometer: "
+ event.accelerationIncludingGravity.x + ", "
+ event.accelerationIncludingGravity.y + ", "
+ event.accelerationIncludingGravity.z
);
}
また、磁力計の場合、次のイベント ハンドラーを登録する必要があります。
if(window.DeviceOrientationEvent){
window.addEventListener("deviceorientation", orientation, false);
}else{
console.log("DeviceOrientationEvent is not supported");
}
ハンドラーを使用:
function orientation(event){
console.log("Magnetometer: "
+ event.alpha + ", "
+ event.beta + ", "
+ event.gamma
);
}
ジャイロスコープのモーション イベントで指定されたフィールドもありますが、これは広くサポートされているようには見えません (たとえば、Samsung Galaxy Note では機能しませんでした)。
GitHubに簡単な作業コードがあります