The Device Motion API allows you to get the acceleration and rotation of the user's device, as well as the orientation of the device relative to the earth's gravity. To use this API, you need to add event listeners to the window object for the devicemotion and deviceorientation events. These events fire at a regular interval, and provide a DeviceMotionEvent and a DeviceOrientationEvent object, respectively. The DeviceMotionEvent object contains the acceleration, accelerationIncludingGravity, rotationRate, and interval properties. The acceleration and accelerationIncludingGravity properties are objects that contain the x, y, and z components of the linear acceleration of the device, in meters per second squared. The rotationRate property is an object that contains the alpha, beta, and gamma components of the angular velocity of the device, in degrees per second. The interval property is a number that indicates the time in milliseconds between successive events. The DeviceOrientationEvent object contains the alpha, beta, and gamma properties, which are numbers that indicate the orientation of the device in degrees, relative to a fixed coordinate system. The alpha property represents the rotation around the z-axis, the beta property represents the rotation around the x-axis, and the gamma property represents the rotation around the y-axis. Here is an example of how to use the Device Motion API:
// Add event listeners for device motion and orientation
window.addEventListener("devicemotion", handleMotion);
window.addEventListener("deviceorientation", handleOrientation);
// Define the motion handler function
function handleMotion(event) {
// Display the acceleration and rotation data
console.log("Acceleration x: " + event.acceleration.x);
console.log("Acceleration y: " + event.acceleration.y);
console.log("Acceleration z: " + event.acceleration.z);
console.log("Rotation rate alpha: " + event.rotationRate.alpha);
console.log("Rotation rate beta: " + event.rotationRate.beta);
console.log("Rotation rate gamma: " + event.rotationRate.gamma);
}
// Define the orientation handler function
function handleOrientation(event) {
// Display the orientation data
console.log("Orientation alpha: " + event.alpha);
console.log("Orientation beta: " + event.beta);
console.log("Orientation gamma: " + event.gamma);
}