通過HTML5 網頁程式碼獲取裝置Sensor值
阿新 • • 發佈:2019-02-08
HTML5 Sensors
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>Web sensor</title> </head> <body> <div id="error"></div> <div id="light"></div> <div id="locate"></div> <div id="gsensor"></div> <div id="gyro"></div> <button onclick="getLightSensor()">光感測試</button><br> <button onclick="getGsensor()">重力感應測試</button><br> <button onclick="getLocation()">WiFi定位</button> <button onclick="getGyro()">Gryo</button> <button onclick="getCompassClb()">CompassClb</button> <script> function getLightSensor() { var x=document.getElementById("light"); var e=document.getElementById('error'); window.addEventListener('devicelight', function(event) { x.innerHTML = 'Lux:' + Math.round(event.value) + 'lux'; },true); } function getGsensor(){ var x=document.getElementById("gsensor"); window.addEventListener("devicemotion", function(event) { var eventacceleration = event.acceleration; x.innerHTML = "acceleration:<br>"+ eventacceleration.x+"<br>"+ eventacceleration.y+"<br>"+ eventacceleration.z }, true); } function getGyro(){ var x=document.getElementById("gyro"); window.addEventListener("deviceorientation", function(event) { x.innerHTML = 'Gyro:<br>' event.alpha+'<br>'+ event.beta+"<br>"+ event.gamma+'<br>'; }, true); } function getCompassClb(){ window.addEventListener("compassneedscalibration", function(event) { alert('You need to calibrate you Compass'); event.preventDefault(); }, true); } </script> <script> var x=document.getElementById("locate"); function getLocation() { if (navigator.geolocation) { navigator.geolocation.watchPosition(showPosition); } else{x.innerHTML="Geolocation is not supported by this browser.";} } function showPosition(position) { x.innerHTML="Latitude: " + position.coords.latitude + "<br />Longitude: " + position.coords.longitude; } </script> </body> </html>