【问题标题】:How to detect device rotation in Cordova?如何在 Cordova 中检测设备旋转?
【发布时间】:2017-07-07 10:25:05
【问题描述】:

我想使用 Cordova 检测实时设备旋转(不是方向,旋转度数)。我使用了设备运动,但我得到了一堆加速度 x y 和 z 值,我如何从中计算旋转?

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

谢谢!

【问题讨论】:

  • 这个插件github.com/apache/cordova-plugin-device-orientation 以度数为您提供设备旋转详细信息。是你要找的吗?
  • 嘿@Ghandi,请看看我给 Devrim 留下的评论。
  • 现在知道了。仍然不确定其他设备运动插件是否可用...将检查
  • 设备运动是我能看到的唯一一个接近这个要求的插件。但是应该使用需要在 x、y、z 坐标之上构建的自定义逻辑来跟踪设备旋转计数。据我检查,插件中还没有现成的解决方案。

标签: cordova phonegap-plugins cordova-plugins phonegap


【解决方案1】:

您可以通过安装评论中提到的plugin 来使用The Screen Orientation API

cordova plugin add cordova-plugin-screen-orientation

那么你可以在deviceReady之后使用事件检测方向变化;

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

screen.orientation.onchange = function({
    console.log(screen.orientation.type);
});

说实话,您应该可以在没有插件的情况下执行此操作,但添加 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;
    } 
}

【讨论】:

  • 谢谢@Devrim,但设备根本不旋转。它是站立的。想象一下,设备在横向模式下粘在一根棍子上,然后你旋转棍子。在这种情况下,方向不会触发,这就是我正在寻找的情况。
  • 嗯,说实话,我不确定@trueicecold。我想你正在寻找设备运动或传感器工具。玩这个插件github.com/apache/cordova-plugin-device-motion
  • 是的,我看到了,但我不知道如何标准化 x、y、z 以检测完整的 360 度摆动...
【解决方案2】:

也许您正在寻找的是 compasscordova-plugin-device-orientation

【讨论】:

    【解决方案3】:

    Device orientation plugin 以度数为您提供设备旋转详细信息。

    但如果您正在寻找检测设备运动,device motion 是我能看到的唯一接近此要求的插件。但是应该使用需要在 x、y、z 坐标之上构建的自定义逻辑来跟踪设备旋转计数。据我检查,插件中还没有现成的解决方案

    【讨论】:

      【解决方案4】:

      您可以使用加速度 x y 和 z 值计算设备的“实时旋转”。

      使用钟摆的类比,假设您确定设备将始终面向用户左右摆动(即在 x 轴上移动),您可以使用 X 值。

      请记住,您不会获得学位值。上次我检查时,iOS 为直立(纵向)返回 0,然后在从一种风景旋转到另一种风景时返回 -9 到 9。

      【讨论】:

        猜你喜欢
        • 2018-10-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多