简体   繁体   中英

Detect device orientation (JS) (alpha, beta, gamma)

I'm trying to detect the device-orientation , of mobile devices, using JavaScript.

I read the documentation, I read other StackOverflow questions, I watched videos on the subject, and this seems super simple, but I just can not get it to work…

This is my current code:

 function handleOrientation(event) { var absolute = event.absolute; var alpha = event.alpha; var beta = event.beta; var gamma = event.gamma; document.querySelector(".deviceAbsolute").innerHTML = absolute; document.querySelector(".deviceAlpha").innerHTML = alpha; document.querySelector(".deviceBeta").innerHTML = beta; document.querySelector(".deviceGamma").innerHTML = gamma; } window.addEventListener("deviceorientation", handleOrientation, true);
 <,doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Build 7</title> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> deviceAbsolute = <span class="deviceAbsolute">no input</span><br> deviceAlpha = <span class="deviceAlpha">no input</span><br> deviceBeta = <span class="deviceBeta">no input</span><br> deviceGamma = <span class="deviceGamma">no input</span> </body> </html>

I uploaded this code to my webspace and tested using iPhone and iPad but nothing happens.


EDIT:

I finally found a working demo: https://sensor-js.xyz/demo.html This works on my iPad and my iPhone, on Safari. – Now the problem is: How did they do it?

Take a look at this: https://developer.mozilla.org/en-US/docs/Web/API/Gyroscope#example

let gyroscope = new Gyroscope({frequency: 60});

gyroscope.addEventListener('reading', e => {
  console.log("Angular velocity along the X-axis " + gyroscope.x);
  console.log("Angular velocity along the Y-axis " + gyroscope.y);
  console.log("Angular velocity along the Z-axis " + gyroscope.z);
});
gyroscope.start();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM