Window: deviceorientation イベント

Baseline 2023

Newly available

Since September 2023, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.

安全なコンテキスト用: この機能は一部またはすべての対応しているブラウザーにおいて、安全なコンテキスト (HTTPS) でのみ利用できます。

deviceorientation イベントは、端末の現在の向きを地球座標フレームと比較した場合に、方角センサーから最新のデータが得られた場合に発生します。このデータは端末内部の方位磁針から収集されます。

詳しくは方向および動きとして示されるデータを参照してください。

このイベントはキャンセル不可で、バブリングしません。

構文

このイベント名を addEventListener() 等のメソッドで使用するか、イベントハンドラープロパティを設定するかしてください。

js
addEventListener("deviceorientation", (event) => {});

ondeviceorientation = (event) => {};

イベント型

DeviceOrientationEvent です。 Event から継承しています。

Event DeviceOrientationEvent

イベントプロパティ

DeviceOrientationEvent.absolute 読取専用

論理値で、端末が絶対に方向データを提供するかどうかを示します。

DeviceOrientationEvent.alpha 読取専用

数値で、端末の Z 軸の回転量を表し、 0 (含む)から 360 (含まない)までの範囲の値で表します。

DeviceOrientationEvent.beta 読取専用

数値で、端末の X 軸の回転量を表し、 -180 (含む)から 180 (含まない)までの範囲の値で表します。これは端末の前後方向の動きを表します。

DeviceOrientationEvent.gamma 読取専用

数値で、端末の Y 軸の回転量を表し、 -90 (含む)から 90 (含まない)までの範囲の値で表します。これは端末の左右方向の動きを表します。

DeviceOrientationEvent.webkitCompassHeading Non-standard 読取専用

数値で、ワールドシステムの Z 軸を中心とした端末の動きと北の方向との差を表し、 0 から 360 の範囲の値で度数で表します。

DeviceOrientationEvent.webkitCompassAccuracy Non-standard 読取専用

コンパスの精度で、偏差が正の値または負の値を意味しています。通常は 10 です。

js
if (window.DeviceOrientationEvent) {
  window.addEventListener(
    "deviceorientation",
    (event) => {
      const rotateDegrees = event.alpha; // alpha: rotation around z-axis
      const leftToRight = event.gamma; // gamma: left to right
      const frontToBack = event.beta; // beta: front back motion

      handleOrientationEvent(frontToBack, leftToRight, rotateDegrees);
    },
    true,
  );
}

const handleOrientationEvent = (frontToBack, leftToRight, rotateDegrees) => {
  // do something amazing
};

仕様書

Specification
DeviceOrientation Event Specification
# deviceorientation
DeviceOrientation Event Specification
# ref-for-dom-window-ondeviceorientation

ブラウザーの互換性

BCD tables only load in the browser

関連情報