1. 程式人生 > >移動端二三事【四】:陀螺儀(重力感應器)實現手機位置、加速度感應以及常見應用。

移動端二三事【四】:陀螺儀(重力感應器)實現手機位置、加速度感應以及常見應用。

效果 防止 size tro 通過 select 代碼 陀螺儀 prime

首先說明一下:陀螺儀感應需在真機環境下進行調試,PC端無效果。

1.獲取感應器

需在window上監聽devicemotion事件,再通過事件對象獲取accelerationIncludingGravity(內置重力加速度感應器)對象。代碼如下:

window.addEventListener(‘devicemotion‘, function(e) {
        var motion = e.accelerationIncludingGravity;
        var x = motion.x;
        var y = motion.y;
        
var z = motion.z; //x,y,z位三個軸方向上的重力加速度 console.log(x); console.log(y); console.log(z); });

x,y,z軸示意圖如下,畫的不好,多多包涵。(Z軸垂直於手機):

技術分享

2.位置與重力加速度:

由上可了解到:獲取的數值為不同方向的重力加速度,所以位置不同x,y,z的數值也會不同:

此處提到的位置包括地理位置與手機擺放位置:

以石家莊(此處為家鄉打call)的地理位置來說(北緯37°27′~38°47′,東經113°30′~115°20′),重力加速度為9.7997。

現假設所在位置的重力加速度為9.8:,則:

將手機平躺放在桌面上,則x軸與y軸重力加速度為0,z軸重力加速度的值為9.8多;

將手機豎立防止(完全豎直),則x軸與z軸的重力加速度為0,y軸重力加速度的值為9.8多;

將手機橫立(完全橫立),則y軸與z軸的重力加速度為0,x軸重力加速度為9.8多。

*可使用手機將以下代碼在服務器環境運行,進行體驗:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content
="width=device-width,user-scalable=no" /> <title>Document</title> <style type="text/css"> #box { width: 200px; height: 200px; background: Red; color: #fff; font-size: 20px; } </style> </head> <body> <div id="box"></div> <script type="text/javascript"> var box = document.querySelector(#box); window.addEventListener(devicemotion, function(e) { var motion = e.accelerationIncludingGravity; var x = motion.x.toFixed(3); var y = motion.y.toFixed(3); var z = motion.z.toFixed(3); box.innerHTML = "x:"+x; box.innerHTML += "<br/>y:"+y; box.innerHTML += "<br/>z:"+z; }); </script> </body> </html>

移動端二三事【四】:陀螺儀(重力感應器)實現手機位置、加速度感應以及常見應用。