如何在Cordova中检测设备旋转?

tru*_*old 5 phonegap-plugins cordova cordova-plugins phonegap

我想用Cordova检测实时设备旋转(而不是方向,以度为单位旋转)。我使用了设备运动,但是得到了一堆加速度xy和z值,如何从中计算出旋转呢?

我想检测一个完整的360度旋转(想象将设备放在棍子或摆锤上,然后敲打使其摆动)。

谢谢!

Abd*_*cin 1

您可以通过安装Gandhi 在评论中提到的插件来使用屏幕方向 API 。

cordova plugin add cordova-plugin-screen-orientation

然后您可以使用事件来检测之后的方向变化deviceReady

window.addEventListener('orientationchange', function(){
    console.log(screen.orientation.type); // e.g. portrait
});
Run Code Online (Sandbox Code Playgroud)

或者

screen.orientation.onchange = function({
    console.log(screen.orientation.type);
});
Run Code Online (Sandbox Code Playgroud)

老实说,您应该能够在没有插件的情况下执行此操作,但添加 cordova 插件会更安全。

当您想要检测 360 度旋转(不包括在内)时,您需要自己计算...类似的东西;

var startingPoint = 0;
window.addEventListener('orientationchange', monitorOrientation); 

function monitorOrientation(e) {
    console.log('Device orientation is: ', e. orientation);

    if(e. orientation == 180 || e.orientation == -180) {
        // You can extend this or remove it completely and increment the variable as you wish i.e. 4x90 = 360
        startingPoint += 180;
    }

    if(startingPoint == 360) {
        // Do whatever you want and reset starting point back to 0
        startingPoint = 0;
    } 
}
Run Code Online (Sandbox Code Playgroud)