Access accelerometer via Javascript in Android?

前端 未结 6 595
夕颜
夕颜 2020-12-02 23:51

Is there any way to access accelerometer data using Javascript on Android\'s browser? I know it supports \"onorientationchange\", but I\'d like to get everything.

C

6条回答
  •  借酒劲吻你
    2020-12-03 00:17

    Making an update to this thread.

    HTML5 lets someone do this. Detecting whether or not an accelerometer is present is easy.

        if (window.DeviceMotionEvent == undefined) {
            //No accelerometer is present. Use buttons. 
            alert("no accelerometer");
        }
        else {
            alert("accelerometer found");
            window.addEventListener("devicemotion", accelerometerUpdate, true);
        }
    

    In the function that you define to receive the accelerometer events, you can look at the accelerationIncludingGravity member.

    function accelerometerUpdate(e) {
       var aX = event.accelerationIncludingGravity.x*1;
       var aY = event.accelerationIncludingGravity.y*1;
       var aZ = event.accelerationIncludingGravity.z*1;
       //The following two lines are just to calculate a
       // tilt. Not really needed. 
       xPosition = Math.atan2(aY, aZ);
       yPosition = Math.atan2(aX, aZ);
    }
    

    More information can be found here: http://dev.w3.org/geo/api/spec-source-orientation.html

提交回复
热议问题