# 偵測裝置方向

## 處理方向事件

Note: gyronorm.js is a polyfill for normalizing the accelerometer and gyroscope data on mobile devices. This is useful for overcoming some of the differences in device support for device orientation.

``````window.addEventListener("deviceorientation", handleOrientation, true);
``````

``````function handleOrientation(event) {
var absolute = event.absolute;
var alpha    = event.alpha;
var beta     = event.beta;
var gamma    = event.gamma;

// Do stuff with the new orientation data
}
``````

### 方向範例

``````<div class="garden">
<div class="ball"></div>
</div>

<pre class="output"></pre>
``````

``````.garden {
position: relative;
width : 200px;
height: 200px;
border: 5px solid #CCC;
}

.ball {
position: absolute;
top   : 90px;
left  : 90px;
width : 20px;
height: 20px;
background: green;
}
``````

``````var ball   = document.querySelector('.ball');
var garden = document.querySelector('.garden');
var output = document.querySelector('.output');

var maxX = garden.clientWidth  - ball.clientWidth;
var maxY = garden.clientHeight - ball.clientHeight;

function handleOrientation(event) {
var x = event.beta;  // In degree in the range [-180,180]
var y = event.gamma; // In degree in the range [-90,90]

output.innerHTML  = "beta : " + x + "\n";
output.innerHTML += "gamma: " + y + "\n";

// Because we don't want to have the device upside down
// We constrain the x value to the range [-90,90]
if (x >  90) { x =  90};
if (x < -90) { x = -90};

// To make computation easier we shift the range of
// x and y to [0,180]
x += 90;
y += 90;

// 10 is half the size of the ball
// It center the positioning point to the center of the ball
ball.style.top  = (maxX*x/180 - 10) + "px";
ball.style.left = (maxY*y/180 - 10) + "px";
}

``````

## 處理動向事件

``window.addEventListener("devicemotion", handleMotion, true);``

### 動向值說明

`DeviceMotionEvent` 物件將提供「裝置位置與方向的變化速度」的相關資訊，並根據 3 組軸線 (可參閱方向與動向資料說明的細節) 提供變化情形。

• `x``：代表由東至西的軸線`
• `y``：代表由南至北的軸線`
• `z``：代表與地面垂直的軸線`

• `alpha``：代表與螢幕 `(或桌機的鍵盤) `垂直的軸線之旋轉率`
• `beta``：代表與螢幕平面 `(或桌機的鍵盤) 由左至右軸線之旋轉率
• `gamma``：代表與螢幕平面 `(或桌機的鍵盤) 由下至上軸線之旋轉率

## 規範

Specification Status Comment
DeviceOrientation Event Specification Editor's Draft Initial specification.

## 瀏覽器相容性

We're converting our compatibility data into a machine-readable JSON format. This compatibility table still uses the old format, because we haven't yet converted the data it contains. Find out how you can help! (en-US)

Feature Chrome Edge Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
`DeviceOrientationEvent` 7.0 (Yes) 3.6[1]
6
? ? ?
`DeviceMotionEvent` (Yes) (Yes) 6 ? ? ?
Feature Android Edge Firefox Mobile (Gecko) IE Phone Opera Mobile Safari Mobile
`DeviceOrientationEvent` 3.0 (Yes) 3.6[1]
6
No support No support 4.2
`DeviceMotionEvent` (Yes) (Yes) 6 ? ? ?

[1] Firefox 3.6 to 5 supported mozOrientation versus the standard `DeviceOrientationEvent` event.