# 偵測裝置方向

## 處理方向事件

```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 positionning 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
Device Orientation Events Working Draft Initial specification.

## 瀏覽器相容性

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

### Gecko 建構說明

1. Firefox 3.6、4、5 均支援 mozOrientation。尚未支援標準的 `DeviceOrientationEvent` 事件。