JavaScriptでの画面の向き検出
Screen Orientation API、orientationメディアクエリ、レガシーorientationchangeイベントを使用してデバイスの向きの変更を検出し対応する方法を解説します。
Orientation
詳細な説明
Screen Orientation API
Screen Orientation APIは、デバイスの現在の向きを検出し変更を監視するためのモダンで標準化された方法を提供します。
現在の向きの読み取り
const orientation = screen.orientation;
console.log(orientation.type); // "landscape-primary"
console.log(orientation.angle); // 0
向きの種類
| タイプ | 角度 | 説明 |
|---|---|---|
| portrait-primary | 0 | 通常の縦向き |
| portrait-secondary | 180 | 上下逆の縦向き |
| landscape-primary | 90 | 横向き、時計回りに回転 |
| landscape-secondary | 270 | 横向き、反時計回りに回転 |
変更の監視
screen.orientation.addEventListener('change', () => {
console.log('新しい向き:', screen.orientation.type);
});
CSSの向きメディアクエリ
@media (orientation: portrait) {
.sidebar { display: none; }
}
@media (orientation: landscape) {
.sidebar { display: block; width: 250px; }
}
注意:CSSのorientationクエリは物理的なデバイスの向きではなく、ビューポートのアスペクト比に基づいています。
ユースケース
フルスクリーンゲーム、動画プレーヤー、モバイル最適化アプリを構築する開発者は、レイアウトの調整やゲームプレイ中の向き固定、回転プロンプトの表示のために向きの変更を検出する必要があります。