繁体   English   中英

如何标准化罗盘输入?

[英]How to normalize the compass input?

我想根据收到的度数旋转罗盘图像。 输入度数介于 0 和 359 之间,因此当我从 0 旋转 -1 度时,图像旋转一整圈并设置为 359:

function setCompass(degrees){
    $("#compass").stop().transition({rotate: -1*degrees +'deg'});
}

我试图通过返回-1而不是359来解决问题,因此我将代码更改为以下内容:

function setCompass(degrees){
    if (degrees>180){degrees=degrees-360}
    $("#compass").stop().transition({rotate: -1*degrees +'deg'});
}

它解决了 0 和 360 上的延迟,但问题转移到了 180。现在当我将设备从 180 旋转到 181 时,它旋转了一个完整的负轮以回到 -179 ! 请建议我如何修改计算,以便我在每个学位上都能获得平滑的变化?

您可以使用一些模公式来确定是顺时针旋转还是逆时针旋转。 使用 jQuery 的data方法保留当前角度(如果您愿意,您可以拥有多个这样的指南针),并允许您作为 CSS 值传递的角度在 0-359 范围之外。

这是它的工作原理:

 function setCompass(degrees){ var curr = $("#compass").data("rotation") || 0; var next = curr + ((degrees - curr)%360 + 180*3) % 360 - 180; $("#compass").data("rotation", next).stop().transition({rotate: -next + 'deg'}); } // Demo with randomly generated angles between 0 and 359 setInterval(function() { setCompass(Math.floor(Math.random()*360)); }, 1000);
 <img id="compass" src="https://i.stack.imgur.com/zdHVn.png" width="100px" height="100px"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.transit/0.9.12/jquery.transit.min.js"></script>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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