The Device Orientation API allows you to get the orientation and motion of the user's device, such as the tilt, rotation, and acceleration. This can be useful for creating interactive and immersive web pages, such as games, animations, or virtual reality. To use this API, you need to listen for the deviceorientation and devicemotion events on the window object, and access the event data in the event handler. For example, you can use the alpha, beta, and gamma properties to get the device's orientation in degrees, and the acceleration and rotationRate properties to get the device's motion in meters per second squared and degrees per second. Here is a simple example of how to use the Device Orientation API:
// Listen for the deviceorientation event
window.addEventListener("deviceorientation", handleOrientation);
// Define a function to handle the orientation data
function handleOrientation(event) {
// Get the orientation angles
var alpha = event.alpha; // The compass direction in degrees
var beta = event.beta; // The front-to-back tilt in degrees
var gamma = event.gamma; // The left-to-right tilt in degrees
// Display the orientation data on the web page
document.getElementById("alpha").innerHTML = "Alpha: " + alpha;
document.getElementById("beta").innerHTML = "Beta: " + beta;
document.getElementById("gamma").innerHTML = "Gamma: " + gamma;
}
// Listen for the devicemotion event
window.addEventListener("devicemotion", handleMotion);
// Define a function to handle the motion data
function handleMotion(event) {
// Get the acceleration and rotation rate
var acc = event.acceleration; // The acceleration in x, y, and z axes in m/s^2
var rot = event.rotationRate; // The rotation rate in alpha, beta, and gamma axes in deg/s
// Display the motion data on the web page
document.getElementById("acc-x").innerHTML = "Acceleration X: " + acc.x;
document.getElementById("acc-y").innerHTML = "Acceleration Y: " + acc.y;
document.getElementById("acc-z").innerHTML = "Acceleration Z: " + acc.z;
document.getElementById("rot-alpha").innerHTML = "Rotation Rate Alpha: " + rot.alpha;
document.getElementById("rot-beta").innerHTML = "Rotation Rate Beta: " + rot.beta;
document.getElementById("rot-gamma").innerHTML = "Rotation Rate Gamma: " + rot.gamma;
}