Categories
JavaScript Answers

How to access accelerometer or gyroscope data from JavaScript?

Spread the love

Sometimes, we want to access accelerometer or gyroscope data from JavaScript.

In this article, we’ll look at how to access accelerometer or gyroscope data from JavaScript.

How to access accelerometer or gyroscope data from JavaScript?

To access accelerometer or gyroscope data from JavaScript, we can listen for the deviceorientation event.

For instance, we write

const handleOrientation = (event) => {
  const absolute = event.absolute;
  const alpha = event.alpha;
  const beta = event.beta;
  const gamma = event.gamma;
  //...
};

window.addEventListener("deviceorientation", handleOrientation, true);

to listen for the deviceorientation event on window with window.addEventListener.

Then we get the event data from the handleOrientation.

absolute is a boolean that indicates whetehr the device is providing orientation data absolutely.

alpha is the motion on the device around the z axis between 0 and 360 degrees inclusive.

beta is the motion on the device around the x axis between 0 and 360 degrees inclusive.

gamma is the motion on the device around the y axis between 0 and 360 degrees inclusive.

Conclusion

To access accelerometer or gyroscope data from JavaScript, we can listen for the deviceorientation event.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *