3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JavaScriptで端末の画面回転角度を取得する

Last updated at Posted at 2018-12-11

仕事中に詰まったのでメモ

画面の回転を取る方法

const angle = window.screen.orientation.angle;

ベンダー対応版

  • mozOrientation
  • msOrientation
const _screen = window.screen;
const _orientation = _screen.orientation || _screen.mozOrientation || _screen.msOrientation;
const angle = _orientation.angle;

iOSのSafariも対応版

  • iOS/Safariは、Screen Orientation APIに非対応
    • window.orientation を使う
const _screen = window.screen;
const _orientation = (_screen 
	&& (_screen.orientation || _screen.mozOrientation || _screen.msOrientation))
	|| ('orientation' in window && {angle: window.orientation})
	|| null;
if (!_orientation || typeof _orientation.angle !== 'number') {
	// 取得失敗
}
const angle = _orientation.angle;

一応これで全端末対応できるはず

2019-06-19追記

window.orientationをそのまま評価すると、 0(回転していない)の時にfalse扱いとなりiOSで正しく取得できない問題があったので修正しました

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?