How to access accelerometer/gyroscope data from Javascript?
The way to do this in 2019+ is to use DeviceOrientation
API. This works in most modern browsers on desktop and mobile.
window.addEventListener("deviceorientation", handleOrientation, true);
After registering your event listener (in this case, a JavaScript
function called handleOrientation()), your listener function
periodically gets called with updated orientation data.The orientation event contains four values:
DeviceOrientationEvent.absolute
DeviceOrientationEvent.alpha
DeviceOrientationEvent.beta
DeviceOrientationEvent.gamma
The event handler function can look something like this:
function handleOrientation(event) {
var absolute = event.absolute;
var alpha = event.alpha;
var beta = event.beta;
var gamma = event.gamma;
// Do stuff with the new orientation data
}
Access accelerometer via Javascript in Android?
As of ICS, Android 4.0, you can use the 'devicemotion' event via a JavaScript event listener to access the accelerometer data. See the W3C documentation on how to access it - http://dev.w3.org/geo/api/spec-source-orientation.html.
Note - The W3C documentation title is named with 'device orientation', but the spec does indeed include 'devicemotion' event documentation.
How do I detect if a device has a gyroscope in a web browser?
If you want to check if gyroscope is present or not, check the parameters that only gyroscope can measure. For example rotation rate is something only gyroscope measures.
Have a look at an example code which says whether gyroscope is present or not:
var gyroPresent = false;
window.addEventListener("devicemotion", function(event){
if(event.rotationRate.alpha || event.rotationRate.beta || event.rotationRate.gamma)
gyroPresent = true;
});
Hope this helps!
EDIT:
Just a small note: Here, the DeviceMotionEvent is used because the rotationRate (and acceleration etc.) can be accessed from this event only. The OP had tried only the DeviceOrientationEvent, so this is worth a mention.
Related Topics
Getting Image Dimensions Using JavaScript File API
Get Path Params in React-Router V4
How to Get All of the Ids with Jquery
How to Replace a Regex Substring Match in JavaScript
Copy to Clipboard in Chrome Extension
What Is Property in Hasownproperty in JavaScript
How to Read Get Data from a Url Using JavaScript
JavaScript Equivalent of Jquery's Extend Method
How to Support Promises in Internet Explorer 11
Chrome Extension: Make It Run Every Page Load
Capture Click on Div Surrounding an Iframe
How to Make 'Setinterval' Behave More in Sync, or How to Use 'Settimeout' Instead
Aggregation Filter After $Lookup
Injecting Js Functions into the Page from a Greasemonkey Script on Chrome
What's Pros and Cons: Putting JavaScript in Head and Putting Just Before the Body Close
Get Position/Offset of Element Relative to a Parent Container