1. Conformance requirements
All diagrams, examples, and notes in this specification are non-normative, as are all sections explicitly marked non-normative. Everything else in this specification is normative.
The key words "MUST", "MUST NOT", "REQUIRED", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in the normative parts of this document are to be interpreted as described in RFC2119. For readability, these words do not appear in all uppercase letters in this specification. [RFC2119]
Requirements phrased in the imperative as part of algorithms (such as "strip any leading space characters" or "return false and abort these steps") are to be interpreted with the meaning of the key word ("must", "should", "may", etc) used in introducing the algorithm.
Conformance requirements phrased as algorithms or specific steps may be implemented in any manner, so long as the end result is equivalent. (In particular, the algorithms defined in this specification are intended to be easy to follow, and not intended to be performant.)
User agents may impose implementation-specific limits on otherwise unconstrained inputs, e.g. to prevent denial of service attacks, to guard against running out of memory, or to work around platform-specific limitations.
Implementations that use ECMAScript to implement the APIs defined in this specification must implement them in a manner consistent with the ECMAScript Bindings defined in the Web IDL specification, as this specification uses that specification’s terminology. [WEBIDL]
The events introduced by this specification implement the Event interface defined in the DOM Specification, [DOM] . Implementations must therefore support this specification.
2. Introduction
This section is non-normative.
This specification provides two new DOM events for obtaining information about the physical orientation and movement of the hosting device. The information provided by the events is not raw sensor data, but rather high-level data which is agnostic to the underlying source of information. Common sources of information include gyroscopes, compasses and accelerometers.
The
first
DOM
event
provided
by
the
specification,
deviceorientation
,
supplies
the
physical
orientation
of
the
device,
expressed
as
a
series
of
rotations
from
a
local
coordinate
frame.
The
second
DOM
event
provided
by
this
specification,
devicemotion
,
supplies
the
acceleration
of
the
device,
expressed
in
Cartesian
coordinates
in
a
coordinate
frame
defined
in
the
device.
It
also
supplies
the
rotation
rate
of
the
device
about
a
local
coordinate
frame.
Where
practically
possible,
the
event
should
provide
the
acceleration
of
the
device’s
center
of
mass.
The following code extracts illustrate basic use of the events.
deviceorientation
events:
window. addEventListener( "deviceorientation" , function ( event) { // process event.alpha, event.beta and event.gamma }, true );
{ alpha: 90 , beta: 0 , gamma: 0 };
To
get
the
compass
heading,
one
would
simply
subtract
alpha
from
360
degrees.
As
the
device
is
turned
on
the
horizontal
surface,
the
compass
heading
is
(360
-
alpha).
beta
is
90,
irrespective
of
what
alpha
and
gamma
are.
{ alpha: 270 - alpha, beta: 0 , gamma: 90 };
devicemotion
events:
window. addEventListener( "devicemotion" , function ( event) { // Process event.acceleration, event.accelerationIncludingGravity, // event.rotationRate and event.interval }, true );
acceleration
of
zero
and
the
following
value
for
accelerationIncludingGravity
:
{ x: 0 , y: 0 , z: 9.8 };
accelerationIncludingGravity
of
zero
and
the
following
value
for
acceleration:
{ x: 0 , y: 0 , z: - 9.8 };
acceleration
and
accelerationIncludingGravity
.
The
device
also
records
a
negative
value
for
rotationRate
.
gamma
:
{ acceleration: { x: v^ 2 / r, y: 0 , z: 0 }, accelerationIncludingGravity: { x: v^ 2 / r, y: 9.8 , z: 0 }, rotationRate: { alpha: 0 , beta: 0 , gamma: - v/ r* 180 / pi} };
3. Scope
This section is non-normative.
This specification is limited to providing DOM events for retrieving information describing the physical orientation and motion of the hosting device. The intended purpose of this API is to enable simple use cases such as those in Use-Cases section. The scope of this specification does not include providing utilities to manipulate this data, such as transformation libraries. Nor does it include providing access to low sensor data, or direct control of these sensors.
4. Model
4.1. Device Orientation
This specification expresses a device’s physical orientation as a series of rotations relative to an implementation-defined reference coordinate frame.
The sequence of rotation steps is a set of intrinsic Tait-Bryan angles of type Z - X' - Y'' ( [EULERANGLES] ) that are applied on the device coordinate system defined in [ACCELEROMETER] and summarized below:
-
x is in the plane of the screen or keyboard and is positive towards the right hand side of the screen or keyboard.
-
y is in the plane of the screen or keyboard and is positive towards the top of the screen or keyboard.
-
z is perpendicular to the screen or keyboard, positive out of the screen or keyboard.
For a mobile device such as a phone or tablet, the device coordinate frame is defined relative to the screen in its standard orientation, typically portrait. This means that slide-out elements such as keyboards are not deployed, and swiveling elements such as displays are folded to their default position. If the orientation of the screen changes when the device is rotated or a slide-out keyboard is deployed, this does not affect the orientation of the coordinate frame relative to the device. For a laptop computer, the device coordinate frame is defined relative to the integrated keyboard.
Note: Users wishing to detect changes in screen orientation should refer to [SCREEN-ORIENTATION] .
Rotations must use the right-hand convention, such that positive rotation around an axis is clockwise when viewed along the positive direction of the axis.
Note:
the
coordinate
system
used
by
this
specification
differs
from
CSS
Transforms
2
§ 4
The
Transform
Rendering
Model
,
where
the
y
axis
is
positive
to
the
bottom
and
rotations
follow
the
left-hand
convention.
Additionally,
rotateSelf()
and
rotate()
,
specified
in
[GEOMETRY-1]
,
apply
rotations
in
an
Z
-
Y'
-
X''
order,
which
differs
from
the
order
specified
here.
A
rotation
represented
by
alpha
,
beta
and
gamma
is
carried
out
by
the
following
steps:
-
Rotate the device frame around its z axis by
alpha
degrees, withalpha
in [0, 360).Device in the initial position, with the reference (XYZ) and body (xyz) frames aligned. Device rotated through angle alpha about z axis, with previous locations of x and y axes shown as x 0 and y 0 . -
Rotate the device frame around its x axis by
beta
degrees, withbeta
in [-180, 180).Device rotated through angle beta about new x axis, with previous locations of y and z axes shown as y 0 and z 0 . -
Rotate the device frame around its y axis by
gamma
degrees, withgamma
in [-90, 90).Device rotated through angle gamma about new y axis, with previous locations of x and z axes shown as x 0 and z 0 .
Note: This choice of angles follows mathematical convention, but means that alpha is in the opposite sense to a compass heading. It also means that the angles do not match the roll-pitch-yaw convention used in vehicle dynamics.
4.1.1. Choice of reference coordinate system
A device’s orientation is always relative to another coordinate system, whose choice influences the kind of information that the orientation conveys as well as the source of the orientation data.
Relative orientation is measured with an accelerometer and a gyroscope, and the reference coordinate system is arbitrary. Consequently, the orientation data provides information about changes relative to the initial position of the device.
Note: In native platform terms, this is similar to a relative OrientationSensor on Windows, a game rotation vector sensor on Android, or the xArbitraryZVertical option for Core Motion.
Absolute orientation is measured with an accelerometer, a gyroscope and a magnetometer, and the reference coordinate system is the Earth’s reference coordinate system .
Note: In native platform terms, this is similar to an absolute OrientationSensor on Windows, a rotation vector sensor on Android, or the xMagneticNorthZVertical option for Core Motion.
4.2. Device Motion
This specification expresses a device’s motion in space by measuring its acceleration and rotation rate, which are obtained from an accelerometer and a gyroscope. The data is provided relative to the device coordinate system summarized in the previous section.
Acceleration is the rate of change of velocity of a device with respect to time. Is is expressed in meters per second squared (m/s 2 ).
Linear acceleration represents the device’s acceleration rate without the contribution of the gravity force. When the device is laying flat on a table, its linear acceleration is 0 m/s 2 .
When the acceleration includes gravity , its value includes the effect of gravity and represents proper acceleration ( [PROPERACCELERATION] ). When the device is in free-fall, the acceleration is 0 m/s 2 . This is less useful in many applications but is provided as a means of providing best-effort support by implementations that are unable to provide linear acceleration (due, for example, to the lack of a gyroscope).
Note: In practice, acceleration with gravity represents the raw readings obtained from an Motion Sensors Explainer § accelerometer , or the [G-FORCE] whereas linear acceleration provides the readings of a Motion Sensors Explainer § linear-acceleration-sensor and is likely a fusion sensor. [MOTION-SENSORS] and [ACCELEROMETER] both contain a more detailed discussion about the different types of accelerometers and accelerations that can be measured.
The rotation rate measures the rate at which the device rotates about a specified axis in the device coordinate system . As with device orientation, rotations must use the right-hand convention, such that positive rotation around an axis is clockwise when viewed along the positive direction of the axis. The rotation rate is measured in degrees per second (deg/s).
Note: [MOTION-SENSORS] and [GYROSCOPE] both contain a more detailed discussion of gyroscopes, rotation rates and measurements.
5. Permissions Policy integration
This specification defines the following policy-controlled features :
-
"
accelerometer
", whose default allowlist is "self
". -
"
gyroscope
", whose default allowlist is "self
". -
"
magnetometer
", whose default allowlist is "self
".
-
The
deviceorientation
event requires the "accelerometer
" and "gyroscope
" features when providing relative orientation data. For the implementation to fall back to absolute orientation data, the "magnetometer
" feature is also used. -
The
deviceorientationabsolute
event requires the "accelerometer
", "gyroscope
" and "magnetometer
" features. -
The
devicemotion
event requires the "accelerometer
" and "gyroscope
" features.
6. Permissions API integration
This specification defines the following default powerful features :
-
"
accelerometer
" -
"
gyroscope
" -
"
magnetometer
"
-
The
deviceorientation
event requires "accelerometer
" and "gyroscope
" when providing relative orientation data. For the implementation to fall back to absolute orientation data, "magnetometer
" is also required. -
The
deviceorientationabsolute
event requires "accelerometer
", "gyroscope
" and "magnetometer
". -
The
devicemotion
event requires "accelerometer
" and "gyroscope
".
7. Task Source
The task source for the tasks mentioned in this specification is the device motion and orientation task source .
8. API
8.1. deviceorientation Event
partial interface Window { [SecureContext ]attribute EventHandler ondeviceorientation ; }; [Exposed =Window ,SecureContext ]interface :
DeviceOrientationEvent Event {(
constructor DOMString ,
type optional DeviceOrientationEventInit = {});
eventInitDict readonly attribute double ?alpha ;readonly attribute double ?beta ;readonly attribute double ?gamma ;readonly attribute boolean absolute ;static Promise <PermissionState >requestPermission (optional boolean =
absolute false ); };dictionary :
DeviceOrientationEventInit EventInit {double ?=
alpha null ;double ?=
beta null ;double ?=
gamma null ;boolean =
absolute false ; };
The
ondeviceorientation
attribute
is
an
event
handler
IDL
attribute
for
the
ondeviceorientation
event
handler
,
whose
event
handler
event
type
is
deviceorientation
.
The
alpha
attribute
must
return
the
value
it
was
initialized
to.
It
represents
the
rotation
around
the
Z
axis
in
the
Z
-
X'
-
Y''
intrinsic
Tait-Bryan
angles
described
in
§ 4.1
Device
Orientation
.
The
beta
attribute
must
return
the
value
it
was
initialized
to.
It
represents
the
rotation
around
the
X'
axis
(produced
after
the
rotation
around
the
Z
axis
has
been
applied)
axis
in
the
Z
-
X'
-
Y''
intrinsic
Tait-Bryan
angles
described
in
§ 4.1
Device
Orientation
.
The
gamma
attribute
must
return
the
value
it
was
initialized
to.
It
represents
the
rotation
around
the
Y''
axis
(produced
after
the
rotation
around
the
Z
and
X'
axes
have
been
applied
in
this
order)
in
the
Z
-
X'
-
Y''
intrinsic
Tait-Bryan
angles
described
in
§ 4.1
Device
Orientation
.
The
absolute
attribute
must
return
the
value
it
was
initialized
to.
It
indicates
whether
relative
orientation
or
absolute
orientation
data
is
being
provided.
requestPermission(
absolute
)
method
steps
are:
-
Let global be the current global object .
-
Let hasTransientActivation be true if this ’s relevant global object has transient activation , and false otherwise.
-
Let result be a new promise in this ’s relevant Realm .
-
Run these steps in parallel :
-
If absolute is true:
-
Let permissions be « " accelerometer ", " gyroscope ", " magnetometer " ».
-
-
Otherwise:
-
Let permissions be « " accelerometer ", " gyroscope " ».
-
-
For each name of permissions :
-
If name ’s permission state is "
prompt
" and hasTransientActivation is false:-
Queue a global task on the device motion and orientation task source given global to reject result with a "
NotAllowedError
"DOMException
. -
Return.
-
-
-
Let permissionState be "
granted
". -
For each name of permissions :
Note: There is no algorithm for requesting multiple permissions at once. However, user agents are encouraged to bundle concurrent requests for different kinds of media into a single user-facing permission prompt.
-
If the result of requesting permission to use name is not "
granted
":
-
-
Queue a global task on the device motion and orientation task source given global to resolve result with permissionState .
-
-
Return result .
Window
)
and
absolute
(a
boolean):
-
Let orientation be null.
-
Let
topLevelTraversable be window ’s navigable ’s top-level traversable . LetvirtualSensorType be "relative-orientation
" if absolute is false, and "absolute-orientation
" otherwise. -
Let document be window ’s associated document .
If
topLevelTraversabledocument ’svirtual sensor mapping[[virtualSensorMapping]]
contains virtualSensorType :-
Let virtualSensor be
topLevelTraversabledocument ’svirtual sensor mapping[[virtualSensorMapping]]
[ virtualSensorType].]'s device sensor . -
If virtualSensor
’s can provide readings flagistrue:not null:-
Set orientation to
the latest readings provided tovirtualSensorwith the " alpha ", " beta ", and " gamma " keys.’s latest saved reading .
Note: orientation will remain null otherwise.
-
-
-
Otherwise:
-
If absolute is false:
-
Set orientation to the device’s relative orientation in the tridimensional plane.
-
-
Otherwise:
-
Set orientation to the device’s absolute orientation in the tridimensional plane.
-
-
-
Let permissions be null.
-
If absolute is false:
-
Set permissions to « " accelerometer ", " gyroscope " ».
-
-
Otherwise:
-
Set permissions to « " accelerometer ", " gyroscope ", " magnetometer " ».
-
-
Let environment be window ’s relevant settings object .
-
Run these steps in parallel :
-
For each permission name in permissions :
-
Let state be the result of getting the current permission state with permission name and environment .
-
If state is not "
granted
", return.
-
-
Queue a global task on the device motion and orientation task source given window to run the following steps:
-
Let z rotation be orientation ’s representation as intrinsic Tait-Bryan angles Z - X' - Y'' along the Z axis, or null if the implementation cannot provide an angle value.
-
If z rotation is not null, limit z rotation ’s precision to 0.1 degrees.
-
Let x rotation be orientation ’s representation as intrinsic Tait-Bryan angles Z - X' - Y'' along the X' axis, or null if the implementation cannot provide an angle value.
-
If x rotation is not null, limit x rotation ’s precision to 0.1 degrees.
-
Let y rotation be orientation ’s representation as intrinsic Tait-Bryan angles Z - X' - Y'' along the Y'' axis, or null if the implementation cannot provide an angle value.
-
If y rotation is not null, limit y rotation ’s precision to 0.1 degrees.
-
Fire an event named event name at window , using
DeviceOrientationEvent
, with thealpha
attribute initialized to z rotation , thebeta
attribute initialized to x rotation , thegamma
attribute initialized to y rotation , and theabsolute
attribute initialized to absolute .
-
-
A
significant
change
in
orientation
indicates
a
difference
in
orientation
values
compared
to
the
previous
ones
that
warrants
the
firing
of
a
deviceorientation
or
deviceorientationabsolute
event.
The
process
of
determining
whether
a
significant
change
in
orientation
has
occurred
is
implementation-defined
,
though
a
maximum
threshold
for
change
of
1
degree
is
recommended.
Implementations
may
also
consider
that
it
has
occurred
if
they
have
reason
to
believe
that
the
page
does
not
have
sufficiently
fresh
data.
Note: Implementations must take § 11 Automation into account to determine whether a significant change in orientation has occurred, so that a virtual sensor reading update causes it to be assessed.
-
Let document be window ’s associated Document .
-
If document ’s visibility state is not "
visible
", return. -
If the implementation cannot provide relative orientation or the resulting absolute orientation data is more accurate:
-
Let absolute be true.
-
Let policies be « "
accelerometer
", "gyroscope
", "magnetometer
" ».
-
-
Otherwise:
-
Let absolute be false.
-
Let policies be « "
accelerometer
", "gyroscope
" ».
-
-
For each policy of policies :
-
If document is not allowed to use the policy-controlled feature named policy , return.
-
-
Invoke fire an orientation event with
deviceorientation
, window , and absolute .
If
an
implementation
can
never
provide
orientation
information,
the
event
should
be
fired
with
the
alpha
,
beta
and
gamma
attributes
set
to
null,
and
the
absolute
attribute
set
to
false.
8.2. deviceorientationabsolute Event
deviceorientationabsolute
event
and
its
ondeviceorientationabsolute
event
handler
IDL
attribute
have
limited
implementation
experience
.
partial interface Window { [SecureContext ]attribute EventHandler ondeviceorientationabsolute ; };
The
ondeviceorientationabsolute
attribute
is
an
event
handler
IDL
attribute
for
the
ondeviceorientationabsolute
event
handler
,
whose
event
handler
event
type
is
deviceorientationabsolute
.
A
deviceorientationabsolute
event
is
completely
analogous
to
the
deviceorientation
event,
except
that
it
must
always
provide
absolute
orientation
data.
-
Invoke fire an orientation event with
deviceorientationabsolute
, window , and true.
If
an
implementation
can
never
provide
absolute
orientation
information,
the
event
should
be
fired
with
the
alpha
,
beta
and
gamma
attributes
set
to
null,
and
the
absolute
attribute
set
to
true.
8.3. devicemotion Event
8.3.1. The DeviceMotionEventAcceleration interface
[Exposed =Window ,SecureContext ]interface {
DeviceMotionEventAcceleration readonly attribute double ?x ;readonly attribute double ?y ;readonly attribute double ?z ; };
The
DeviceMotionEventAcceleration
interface
represents
the
device’s
acceleration
as
described
in
§ 4.2
Device
Motion
.
It
has
the
following
associated
data:
- x axis acceleration
-
The device’s acceleration rate along the X axis, or null. It is initially null.
- y axis acceleration
-
The device’s acceleration rate along the Y axis, or null. It is initially null.
- z axis acceleration
-
The device’s acceleration rate along the Z axis, or null. It is initially null.
The
x
getter
steps
are
to
return
the
value
of
this
’s
x
axis
acceleration
.
The
y
getter
steps
are
to
return
the
value
of
this
’s
y
axis
acceleration
.
The
z
getter
steps
are
to
return
the
value
of
this
’s
z
axis
acceleration
.
8.3.2. The DeviceMotionEventRotationRate interface
[Exposed =Window ,SecureContext ]interface {
DeviceMotionEventRotationRate readonly attribute double ?alpha ;readonly attribute double ?beta ;readonly attribute double ?gamma ; };
The
DeviceMotionEventRotationRate
interface
represents
the
device’s
rotation
rate
as
described
in
§ 4.2
Device
Motion
.
It
has
the
following
associated
data:
- x axis rotation rate
-
The device’s rotation rate about the X axis, or null. It is initially null.
- y axis rotation rate
-
The device’s rotation rate about the Y axis, or null. It is initially null.
- z axis rotation rate
-
The device’s rotation rate about the Z axis, or null. It is initially null.
The
alpha
getter
steps
are
to
return
the
value
of
this
’s
x
axis
rotation
rate
.
The
beta
getter
steps
are
to
return
the
value
of
this
’s
y
axis
rotation
rate
.
The
gamma
getter
steps
are
to
return
the
value
of
this
’s
z
axis
rotation
rate
.
8.3.3. The DeviceMotionEvent interface
partial interface Window { [SecureContext ]attribute EventHandler ondevicemotion ; }; [Exposed =Window ,SecureContext ]interface :
DeviceMotionEvent Event {(
constructor DOMString ,
type optional DeviceMotionEventInit = {});
eventInitDict readonly attribute DeviceMotionEventAcceleration ?acceleration ;readonly attribute DeviceMotionEventAcceleration ?accelerationIncludingGravity ;readonly attribute DeviceMotionEventRotationRate ?rotationRate ;readonly attribute double interval ;static Promise <PermissionState >requestPermission (); };dictionary {
DeviceMotionEventAccelerationInit double ?=
x null ;double ?=
y null ;double ?=
z null ; };dictionary {
DeviceMotionEventRotationRateInit double ?=
alpha null ;double ?=
beta null ;double ?=
gamma null ; };dictionary :
DeviceMotionEventInit EventInit {DeviceMotionEventAccelerationInit ;
acceleration DeviceMotionEventAccelerationInit ;
accelerationIncludingGravity DeviceMotionEventRotationRateInit ;
rotationRate double = 0; };
interval
The
ondevicemotion
attribute
is
an
event
handler
IDL
attribute
for
the
ondevicemotion
event
handler
,
whose
event
handler
event
type
is
devicemotion
.
The
acceleration
attribute
must
return
the
value
it
was
initialized
to.
When
the
object
is
created,
this
attribute
must
be
initialized
to
null.
It
represents
the
device’s
linear
acceleration
.
The
accelerationIncludingGravity
attribute
must
return
the
value
it
was
initialized
to.
When
the
object
is
created,
this
attribute
must
be
initialized
to
null.
It
represents
the
device’s
acceleration
with
gravity
.
The
rotationRate
attribute
must
return
the
value
it
was
initialized
to.
When
the
object
is
created,
this
attribute
must
be
initialized
to
null.
It
represents
the
device’s
rotation
rate
.
The
interval
attribute
must
return
the
value
it
was
initialized
to.
It
represents
the
interval
at
which
data
is
obtained
from
the
underlying
hardware
and
must
be
expressed
in
milliseconds
(ms).
It
is
constant
to
simplify
filtering
of
the
data
by
the
Web
application.
requestPermission()
method
steps
are:
-
Let global be the current global object .
-
Let hasTransientActivation be true if this ’s relevant global object has transient activation , and false otherwise.
-
Let result be a new promise in this ’s relevant Realm .
-
Run these steps in parallel :
-
Let permissions be « " accelerometer ", " gyroscope " ».
-
For each name of permissions :
-
If name ’s permission state is "
prompt
" and hasTransientActivation is false:-
Queue a global task on the device motion and orientation task source given global to reject result with a "
NotAllowedError
"DOMException
. -
Return.
-
-
-
Let permissionState be "
granted
". -
For each name of permissions :
Note: There is no algorithm for requesting multiple permissions at once. However, user agents are encouraged to bundle concurrent requests for different kinds of media into a single user-facing permission prompt.
-
If the result of requesting permission to use name is not "
granted
":
-
-
Queue a global task on the device motion and orientation task source given global to resolve result with permissionState .
-
-
Return result .
-
Let document be window ’s associated Document .
-
If document ’s visibility state is not "
visible
", return. -
For each policy of « "
accelerometer
", "gyroscope
" »:-
If document is not allowed to use the policy-controlled feature named policy , return.
-
-
Let
topLevelTraversablevirtualSensorMapping bewindowdocument ’snavigable[[virtualSensorMapping]]
.’s top-level traversable . -
Let platformLinearAcceleration be null.
-
If
topLevelTraversablevirtualSensorMapping’s virtual sensor mappingcontains "linear-acceleration
":-
Let virtualSensor be
topLevelTraversablevirtualSensorMapping’s virtual sensor mapping["linear-acceleration
"]."]'s device sensor . -
If virtualSensor
’s can provide readings flagistrue,not null, then set platformLinearAcceleration tothe latest readings provided tovirtualSensor.’s latest saved reading .
-
-
Otherwise, if the implementation is able to provide linear acceleration :
-
Set platformLinearAcceleration to the device’s linear acceleration along the X, Y and Z axes.
-
-
Let acceleration be null.
-
If platformLinearAcceleration is not null:
-
Set acceleration to a new
DeviceMotionEventAcceleration
created in window ’s realm . -
Set acceleration ’s x axis acceleration to platformLinearAcceleration ’s value along the X axis, or null if it cannot be provided.
-
If acceleration ’s x axis acceleration is not null, limit its precision to no more than 0.1 m/s 2 .
-
Set acceleration ’s y axis acceleration to platformLinearAcceleration ’s value along the Y axis, or null if it cannot be provided.
-
If acceleration ’s y axis acceleration is not null, limit its precision to no more than 0.1 m/s 2 .
-
Set acceleration ’s z axis acceleration to platformLinearAcceleration ’s value along the Z axis, or null if it cannot be provided.
-
If acceleration ’s z axis acceleration is not null, limit its precision to no more than 0.1 m/s 2 .
-
-
Let platformAccelerationIncludingGravity be null.
-
If
topLevelTraversablevirtualSensorMapping’s virtual sensor mappingcontains "accelerometer
":-
Let virtualSensor be
topLevelTraversablevirtualSensorMapping’s virtual sensor mapping["accelerometer
"]."]'s device sensor . -
If virtualSensor
’s can provide readings flagistrue,not null, then set platformAccelerationIncludingGravity tothe latest readings provided tovirtualSensor.’s latest saved reading .
-
-
Otherwise, if the implementation is able to provide acceleration with gravity :
-
Set platformAccelerationIncludingGravity to the device’s linear acceleration along the X, Y and Z axes.
-
-
Let accelerationIncludingGravity be null.
-
If platformAccelerationIncludingGravity is not null:
-
Set accelerationIncludingGravity to a new
DeviceMotionEventAcceleration
created in window ’s realm . -
Set accelerationIncludingGravity ’s x axis acceleration to platformAccelerationIncludingGravity ’s value along the X axis, or null if it cannot be provided.
-
If accelerationIncludingGravity ’s x axis acceleration is not null, limit its precision to no more than 0.1 m/s 2 .
-
Set accelerationIncludingGravity ’s y axis acceleration to platformAccelerationIncludingGravity ’s value along the Y axis, or null if it cannot be provided.
-
If accelerationIncludingGravity ’s y axis acceleration is not null, limit its precision to no more than 0.1 m/s 2 .
-
Set accelerationIncludingGravity ’s z axis acceleration to platformAccelerationIncludingGravity ’s value along the Z axis, or null if it cannot be provided.
-
If accelerationIncludingGravity ’s z axis acceleration is not null, limit its precision to no more than 0.1 m/s 2 .
-
-
Let platformRotationRate be null.
-
If
topLevelTraversablevirtualSensorMapping’s virtual sensor mappingcontains "gyroscope
":-
Let virtualSensor be
topLevelTraversablevirtualSensorMapping’s virtual sensor mapping["gyroscope
"]."]'s device sensor . -
If virtualSensor ’s
can provide readings flagistrue,not null, then set platformRotationRate tothe latest readings provided tovirtualSensor.’s latest saved reading .
-
-
Otherwise, if the implementation is able to provide rotation rate :
-
Set platformRotationRate to the device’s rotation rate about the X, Y and Z axes.
-
-
Let rotationRate be null.
-
If platformRotationRate is not null:
-
Set rotationRate to a new
DeviceMotionEventRotationRate
created in window ’s realm . -
Set rotationRate ’s x axis rotation rate to platformRotationRate ’s value about the X axis, or null if it cannot be provided.
-
If rotationRate ’s x axis rotation rate is not null, limit its precision to no more than 0.1 deg/s.
-
Set rotationRate ’s y axis rotation rate to platformRotationRate ’s value about the Y axis, or null if it cannot be provided.
-
If rotationRate ’s y axis rotation rate is not null, limit its precision to no more than 0.1 deg/s.
-
Set rotationRate ’s z axis rotation rate to platformRotationRate ’s value about the Z axis, or null if it cannot be provided.
-
If rotationRate ’s z axis rotation rate is not null, limit its precision to no more than 0.1 deg/s.
-
-
Let environment be window ’s relevant settings object .
-
Run these steps in parallel :
-
For each permission name in « " accelerometer ", " gyroscope " »:
-
Let state be the result of getting the current permission state with permission name and environment .
-
If state is not "
granted
", return.
-
-
Queue a global task on the device motion and orientation task source given window to run the following steps:
-
Fire an event named
devicemotion
at window , usingDeviceMotionEvent
, with theacceleration
attribute initialized to acceleration , theaccelerationIncludingGravity
attribute initialized to accelerationIncludingGravity , therotationRate
attribute initialized to rotationRate , and theinterval
attribute initialized to interval .
-
-
If
an
implementation
can
never
provide
motion
information,
the
event
should
be
fired
with
the
acceleration
,
accelerationIncludingGravity
and
rotationRate
attributes
set
to
null.
9. Security and privacy considerations
The API defined in this specification can be used to obtain information from hardware sensors, such as accelerometer, gyroscope and magnetometer. Provided data may be considered as sensitive and could become a subject of attack from malicious web pages. The calibration of accelerometers, gyroscopes and magnetometers may reveal persistent details about the particular sensor hardware [SENSORID] . The main attack vectors can be categorized into following categories:
-
Monitoring of a user input [TOUCH]
-
Location tracking [INDOORPOS]
-
User identification [FINGERPRINT]
In
light
of
that,
implementations
may
consider
visual
indicators
to
signify
the
use
of
sensors
by
the
web
page.
Additionally,
this
specification
requires
users
to
give
express
permission
for
the
user
agent
to
provide
device
motion
and/or
orientation
data
via
the
requestPermission()
API
calls.
Furthermore, to minimize privacy risks, the chance of fingerprinting and other attacks the implementations must:
-
fire events only when a navigable 's active document 's visibility state is "
visible
", -
implement § 5 Permissions Policy integration so that events are fired on child navigables (including but not restricted to cross-origin ones) only if allowed by the top-level traversable ,
-
fire events on a navigable 's active windows only when its relevant settings object is a secure context ,
-
limit precision of attribute values as described in the previous sections.
Additionally, implementing these items may also have a beneficial impact on the battery life of mobile devices.
10. Use-Cases and Requirements
10.1. Use-Cases
This section is non-normative.10.1.1. Controlling a game
This section is non-normative.A gaming Web application monitors the device’s orientation and interprets tilting in a certain direction as a means to control an on-screen sprite.
10.1.2. Gesture recognition
This section is non-normative.A Web application monitors the device’s acceleration and applies signal processing in order to recognize certain specific gestures. For example, using a shaking gesture to clear a web form.
10.1.3. Mapping
This section is non-normative.A mapping Web application uses the device’s orientation to correctly align the map with reality.
10.2. Requirements
This section is non-normative.-
The specification must provide data that describes the physical orientation in space of the device.
-
The specification must provide data that describes the motion in space of the device.
-
The specification must allow Web applications to register for changes in the device’s orientation.
-
The specification must be agnostic to the underlying sources of orientation and motion data.
-
The specification must use the existing DOM event framework.
11. Automation
This specification can pose a challenge to test authors, as the events defined here depend on the presence of physical hardware whose readings cannot be easily controlled.
To address this challenge, this document builds upon the [WEBDRIVER2] extension commands and infrastructure laid out by Generic Sensor API § 9 Automation . This was chosen over the option of developing completely new and independent infrastructure with separate extension commands because there is significant overlap between the two specifications: not only does testing the [GENERIC-SENSOR] specification present similar challenges, but many derived APIs (e.g. [GYROSCOPE] ) obtain and provide similar information.
This specification only requires implementations to support the Generic Sensor API § 9 Automation section of the [GENERIC-SENSOR] specification, not its interfaces and events.
11.1. Additional implementation requirements
Several aspects of the manner in which the user agent interacts with the underlying hardware or operating system are implementation-defined . For instance, the § 4 Model and § 8 API sections do not mandate:
That readings must be retrieved in a specific way.
When or how the user agent connects to one or more providers of readings.
Which types or data structures need to be used to store readings.
Whether readings obtained from the platform or operating system are shared across documents .
For automation support to work, specifically in the context of integrating with Generic Sensor API § 9 Automation , some of this behavior needs to be specified in more detail.
The
Document
interface
must
have
a
[[virtualSensorMapping]]
internal
slot,
a
map
of
virtual
sensor
types
to
orientation
event
platform
sensor-likes
.
A
orientation
event
platform
sensor-like
is
a
platform
sensor-like
struct
with
the
following
items:
A sampling frequency (a number). It represents either the frequency with which the user agent either polls the underlying hardware for readings, or the frequency at which the underlying hardware should notify the user agent of new readings.
A device sensor (a virtual sensor or null).
Document
document
:For each platformSensorLike of document .
[[virtualSensorMapping]]
's values :Remove platformSensorLike from platformSensorLike ’s device sensor 's connected platform sensors .
Window
),
virtualSensorType
(a
string),
and
samplingFrequency
(a
number)
perform
the
following
steps.
They
return
a
boolean.
Let topLevelTraversable be window ’s navigable 's top-level traversable .
If topLevelTraversable ’s virtual sensor mapping does not contain virtualSensorType , return false.
Let virtualSensor be topLevelTraversable ’s virtual sensor mapping [ virtualSensorType ].
Let platformSensorLike be null.
If window ’s associated Document 's
[[virtualSensorMapping]]
contains virtualSensorType :Set platformSensorLike to window ’s associated Document 's
[[virtualSensorMapping]]
[ virtualSensorType ].
Otherwise:
Set platformSensorLike to a new orientation event platform sensor-like whose device sensor is null.
Set window ’s associated Document 's
[[virtualSensorMapping]]
[ virtualSensorType ] to platformSensorLike .If samplingFrequency is less than virtualSensor ’s minimum sampling frequency or greater than virtualSensor ’s maximum sampling frequency , return true.
Note: platformSensorLike ’s device sensor will remain null.
Set platformSensorLike ’s sampling frequency to samplingFrequency .
If virtualSensor ’s can provide readings flag is false, return true.
Note: platformSensorLike ’s device sensor will remain null.
If platformSensorLike ’s device sensor is null:
Set platformSensorLike ’s device sensor to virtualSensor .
Append platformSensorLike to virtualSensor ’s connected platform sensors .
If virtualSensor ’s latest saved readings is not null:
In an implementation-defined way, make virtualSensor ’s latest saved readings available to platformSensorLike .
Return true.
Window
)
and
virtualSensorType
(a
string),
perform
the
following
steps.
They
return
a
boolean.
If window ’s associated Document 's
[[virtualSensorMapping]]
does not contain virtualSensorType , return false.Let platformSensorLike be window ’s associated Document 's
[[virtualSensorMapping]]
[ virtualSensorType ].If platformSensorLike ’s device sensor is null, return true.
Remove platformSensorLike from platformSensorLike ’s device sensor 's connected platform sensors .
Return true.
11.2. Device Orientation Automation
Automation
support
for
the
deviceorientation
event
is
built
upon
virtual
sensors
that
represent
accelerometers,
gyroscopes
and,
optionally,
magnetometers.
Orientation data retrieved from the platform by the user agent comes from accelerometers, gyroscopes and, optionally, magnetometers. Contrary to motion data, however, these lower-level readings must be transformed into Euler angles in the formation described in § 4.1 Device Orientation . Furthermore, the platform might provide extra APIs to the user agent that already perform some of those conversions from raw acceleration and rotation data.
Therefore, instead of requiring implementations (and automation users) to provide orientation readings via lower-level virtual sensors which use different units of measurement, this specification defines extra virtual sensor types for relative and orientation data in the format used by this specification.
deviceorientation
or
deviceorientationabsolute
is
added
to
a
Window
window
,
the
process
for
attempting
to
connect
to
the
underlying
hardware
must
be
as
follows:
Let virtualSensorType be " relative-orientation " if the user agent is attempting to connect to hardware that provides relative orientation data, and " absolute-orientation " otherwise.
Let interval be implementation-defined interval in seconds at which implementations either poll for new readings or request new readings to be delivered.
If connect to a virtual sensor with window , virtualSensorType , and (1 / interval ) returns false, abort these steps and continue with the regular implementation-defined steps to connect to real hardware.
In an implementation-defined way, start the process that the user agent uses to determine whether a significant change in orientation has occurred.
deviceorientation
or
deviceorientationabsolute
is
removed
from
a
Window
window
and
the
user
agent
determines
it
should
stop
retrieving
readings
from
the
underlying
hardware:
Let virtualSensorType be " relative-orientation " if the user agent is attempting to disconnect from hardware that provides relative orientation data, and " absolute-orientation " otherwise.
If disconnect from a virtual sensor with window and virtualSensorType returns false, abort these steps and continue with the regular implementation-defined steps to disconnect from real hardware.
11.1.1.
11.2.1.
Parse
orientation
reading
data
algorithm
Object
parameters
:
-
Let alpha be the result of invoking get a property from parameters with "
alpha
". -
If alpha is not a
Number
, or its value is NaN , +∞, or −∞, return undefined . -
If alpha is not in the range [0, 360), then return undefined .
-
Let beta be the result of invoking get a property from parameters with "
beta
". -
If beta is not a
Number
, or its value is NaN , +∞, or −∞, return undefined . -
If beta is not in the range [-180, 180), then return undefined .
-
Let gamma be the result of invoking get a property from parameters with "
gamma
". -
If gamma is not a
Number
, or its value is NaN , +∞, or −∞, return undefined . -
If gamma is not in the range [-90, 90), then return undefined .
-
Let reading be a new map .
-
Set reading ["
alpha
"] to alpha . -
Set reading ["
beta
"] to beta . -
Set reading ["
gamma
"] to gamma . -
Return reading .
Note: reading is defined as a map in the algorithm above to prevent a dependency on the sensor reading concept from the [GENERIC-SENSOR] specification. They should be interchangeable for the purposes of the algorithm above.
11.1.2.
11.2.2.
The
"absolute-orientation"
virtual
sensor
type
The per-type virtual sensor metadata map must have the following entry :
-
- key
-
"
absolute-orientation
" - value
-
A virtual sensor metadata whose reading parsing algorithm is parse orientation data reading .
11.1.3.
11.2.3.
The
"relative-orientation"
virtual
sensor
type
The per-type virtual sensor metadata map must have the following entry :
-
- key
-
"
relative-orientation
" - value
-
A virtual sensor metadata whose reading parsing algorithm is parse orientation data reading .
11.2.
11.3.
Device
Motion
Automation
The motion data retrieved from the platform by the user agent comes from accelerometers and gyroscopes. This specification defines certain per-type virtual sensor metadata entries that are shared with the [ACCELEROMETER] and [GYROSCOPE] specifications.
Accelerometer virtual sensors are used to provide acceleration with gravity data to the platform. Linear Acceleration virtual sensors are used to provide linear acceleration data to the platform. Gyroscope virtual sensors are used to provide rotation rate data to the platform.
devicemotion
is
added
to
a
Window
window
,
the
process
for
attempting
to
connect
to
the
underlying
hardware
must
be
as
follows:
Let virtualSensorType be null.
If the user agent needs to connect to hardware that provides acceleration with gravity data, set virtualSensorType to " accelerometer ".
Otherwise, if the user agent needs to connect to hardware that provides linear acceleration data, set virtualSensorType to " linear-acceleration ".
Otherwise, if the user agent needs to connect to hardware that provides rotation rate data, set virtualSensorType to " gyroscope ".
Let interval be implementation-defined interval in seconds at which implementations either poll for new readings or request new readings to be delivered.
If connect to a virtual sensor with window , virtualSensorType , and (1 / interval ) returns false, abort these steps and continue with the regular implementation-defined steps to connect to real hardware.
devicemotion
is
removed
from
a
Window
window
and
the
user
agent
determines
it
should
stop
retrieving
readings
from
the
underlying
hardware:
Let virtualSensorType be null.
If the user agent needs to disconnect from hardware that provides acceleration with gravity data, set virtualSensorType to " accelerometer ".
Otherwise, if the user agent needs to disconnect from hardware that provides linear acceleration data, set virtualSensorType to " linear-acceleration ".
Otherwise, if the user agent needs to disconnect from hardware that provides rotation rate data, set virtualSensorType to " gyroscope ".
If disconnect from a virtual sensor with window and virtualSensorType returns false, abort these steps and continue with the regular implementation-defined steps to disconnect from real hardware.
11.2.1.
11.3.1.
The
"accelerometer"
virtual
sensor
type
The per-type virtual sensor metadata map must have the following entry :
- key
-
"
accelerometer
" - value
-
A virtual sensor metadata whose reading parsing algorithm is parse xyz reading .
11.2.2.
11.3.2.
The
"linear-acceleration"
virtual
sensor
type
The per-type virtual sensor metadata map must have the following entry :
- key
-
"
linear-acceleration
" - value
-
A virtual sensor metadata whose reading parsing algorithm is parse xyz reading .
11.2.3.
11.3.3.
The
"gyroscope"
virtual
sensor
type
The per-type virtual sensor metadata map must have the following entry :
- key
-
"
gyroscope
" - value
-
A virtual sensor metadata whose reading parsing algorithm is parse xyz reading .
A Examples
This section is non-normative.A.1 Calculating compass heading
This section is non-normative.
The following worked example is intended as an aid to users of the DeviceOrientation event.
Introduction section provided an example of using the DeviceOrientation event to obtain a compass heading when the device is held with the screen horizontal. This example shows how to determine the compass heading that the user is facing when holding the device with the screen approximately vertical in front of them. An application of this is an augmented-reality system.
More precisely, we wish to determine the compass heading of the horizontal component of a vector which is orthogonal to the device’s screen and pointing out of the back of the screen.
If v represents this vector in the rotated device body frame xyz, then v is as follows.
The transformation of v due to the rotation about the z axis can be represented by the following rotation matrix.
The transformation of v due to the rotation about the x axis can be represented by the following rotation matrix.
The transformation of v due to the rotation about the y axis can be represented by the following rotation matrix.
If R represents the full rotation matrix of the device in the earth frame XYZ, then since the initial body frame is aligned with the earth, R is as follows.
If v' represents the vector v in the earth frame XYZ, then since the initial body frame is aligned with the earth, v' is as follows.
The compass heading θ is given by
provided that β and γ are not both zero.
The
compass
heading
calculation
above
can
be
represented
in
JavaScript
as
follows
to
return
the
correct
compass
heading
when
the
provided
parameters
are
defined,
not
null
and
represent
absolute
values.
var degtorad= Math. PI/ 180 ; // Degree-to-Radian conversion function compassHeading( alpha, beta, gamma) { var _x= beta? beta* degtorad: 0 ; // beta value var _y= gamma? gamma* degtorad: 0 ; // gamma value var _z= alpha? alpha* degtorad: 0 ; // alpha value var cX= Math. cos( _x); var cY= Math. cos( _y); var cZ= Math. cos( _z); var sX= Math. sin( _x); var sY= Math. sin( _y); var sZ= Math. sin( _z); // Calculate Vx and Vy components var Vx= - cZ* sY- sZ* sX* cY; var Vy= - sZ* sY+ cZ* sX* cY; // Calculate compass heading var compassHeading= Math. atan( Vx/ Vy); // Convert compass heading to use whole unit circle if ( Vy< 0 ) { compassHeading+= Math. PI; } else if ( Vx< 0 ) { compassHeading+= 2 * Math. PI; } return compassHeading* ( 180 / Math. PI); // Compass Heading (in degrees) }
As a consistency check, if we set γ = 0, then
as expected.
Alternatively, if we set β = 90, then
as expected.
A.2 Alternate device orientation representations
This section is non-normative.
Describing orientation using Tait-Bryan angles can have some disadvantages such as introducing gimbal lock [GIMBALLOCK] . Depending on the intended application it can be useful to convert the Device Orientation values to other rotation representations.
The first alternate orientation representation uses rotation matrices. By combining the component rotation matrices provided in the worked example above we can represent the orientation of the device body frame as a combined rotation matrix.
If R represents the rotation matrix of the device in the earth frame XYZ, then since the initial body frame is aligned with the earth, R is as follows.
absolute
values.
var degtorad= Math. PI/ 180 ; // Degree-to-Radian conversion function getRotationMatrix( alpha, beta, gamma) { var _x= beta? beta* degtorad: 0 ; // beta value var _y= gamma? gamma* degtorad: 0 ; // gamma value var _z= alpha? alpha* degtorad: 0 ; // alpha value var cX= Math. cos( _x); var cY= Math. cos( _y); var cZ= Math. cos( _z); var sX= Math. sin( _x); var sY= Math. sin( _y); var sZ= Math. sin( _z); // // ZXY rotation matrix construction. // var m11= cZ* cY- sZ* sX* sY; var m12= - cX* sZ; var m13= cY* sZ* sX+ cZ* sY; var m21= cY* sZ+ cZ* sX* sY; var m22= cZ* cX; var m23= sZ* sY- cZ* cY* sX; var m31= - cX* sY; var m32= sX; var m33= cX* cY; return [ m11, m12, m13, m21, m22, m23, m31, m32, m33]; };
Another alternate representation of device orientation data is as Quaternions. [QUATERNIONS]
If q represents the unit quaternion of the device in the earth frame XYZ, then since the initial body frame is aligned with the earth, q is as follows.
absolute
values
and
those
parameters
are
not
null.
var degtorad= Math. PI/ 180 ; // Degree-to-Radian conversion function getQuaternion( alpha, beta, gamma) { var _x= beta? beta* degtorad: 0 ; // beta value var _y= gamma? gamma* degtorad: 0 ; // gamma value var _z= alpha? alpha* degtorad: 0 ; // alpha value var cX= Math. cos( _x/ 2 ); var cY= Math. cos( _y/ 2 ); var cZ= Math. cos( _z/ 2 ); var sX= Math. sin( _x/ 2 ); var sY= Math. sin( _y/ 2 ); var sZ= Math. sin( _z/ 2 ); // // ZXY quaternion construction. // var w= cX* cY* cZ- sX* sY* sZ; var x= sX* cY* cZ- cX* sY* sZ; var y= cX* sY* cZ+ sX* cY* sZ; var z= cX* cY* sZ+ sX* sY* cZ; return [ w, x, y, z]; }
We can check that a Unit Quaternion has been constructed correctly using Lagrange’s four-square theorem
as expected.
Acknowledgments
Lars Erik Bolstad, Dean Jackson, Claes Nilsson, George Percivall, Doug Turner, Matt Womer, Chris Dumez
12. Changes
This section summarizes substantial changes and notable editorial improvements to guide review. Full details are available from the commit log . Changes since the Candidate Recommendation 2016-08-18 :
-
Add Permissions Policy integration, which supersedes the previous requirement of only firing events on iframes that were same-origin with the top-level frame
-
Add note to implementers about bundling permission requests
-
Export powerful features Accelerometer, Gyroscope and Magnetometer
-
Add Permissions API integration, start requiring requestPermission() usage
-
editorial: Define API section more normatively and with more dfns
-
editorial: Reorder acceleration explanation in Device Motion Model section
-
editorial: Update explanations of the device rotation and motion references
-
editorial: Use more precise event handling terms, modernize others
-
editorial: Refer to [SCREEN-ORIENTATION] instead of the orientation change event
-
editorial: Reword requirements in "Security and privacy considerations"
-
Mark use cases and requirements and examples sections non-normative
-
Remove the oncompassneedscalibration event
-
Update references to "triggered by user activation", now referred to as "transient activation"
-
Align with DOM phrasing on firing events
-
Add a note about acceleration properties for DeviceMotionEvent
-
Add a note explaining how the coordinate system differs from the CSS coordinate system
-
Require no more precise than 0.1 degrees, 0.1 degrees per second, 0.1 meters per second squared to mitigate a passive fingerprinting issue
-
Update constructor definition in IDL with the Web IDL
-
Add explicit [Exposed] to interfaces
-
Update IDL dictionaries with new dictionary defaulting setup
-
Note the deviceorientationabsolute event and its ondeviceorientationabsolute event handler IDL attribute have limited implementation experience
-
Add requestPermission() API static operation to both DeviceOrientationEvent and DeviceMotionEvent
-
Add [SecureContext] to event handlers ondeviceorientation, ondevicemotion and ondeviceorientationabsolute
-
Restrict all interfaces to secure contexts
-
Remove [NoInterfaceObject] from DeviceAcceleration and DeviceRotationRate
-
Make security and privacy considerations normative
-
Add the ondeviceorientationabsolute event handler attribute into the IDL block (was only in prose)
-
Remove '?' from dictionary members of DeviceMotionEventInit
-
Use [Exposed=Window] extended attribute