繁体   English   中英

如何顺时针或逆时针旋转图像,以较短者为准?

[英]How to rotate an image clockwise or counterclockwise, whichever is shorter?

我正在制作一个网页,其中包含一个带箭头的时钟。 当用户点击一小时时,箭头会旋转以指向他/她点击的内容。

我正在使用jQuery图像旋转插件(jQueryRotate)来旋转箭头。

以下是计算要旋转的度数的当前代码:

var numTiles = $("ul li").size(); // Number of tiles is however many are listed in the UL, which is 12  
var sel = 0; // Default hour selection  
var rot = 0; // Default rotation is at the top (0 degrees)  
var gap = 360 / numTiles; // Degrees between each tile

function rotateArrow(num) {  
  rot = num * gap;  
  $("#arrow").rotateAnimation(rot);  
  sel = num;  
}  

当用户单击其中一个小时时,它会将num作为值1到12传递。

它工作正常,但问题是如果箭头指向1点钟,并且用户点击11点钟,箭头顺时针旋转300度,此时逆时针旋转60度会更有意义。

那么,我怎么能写一个方程来取当前小时(num)和小时点击(sel),并输出一个正数或负数,它等于最有效的旋转度数,而不是只在一个方向旋转?

任何建议表示赞赏。 如果您有任何疑问,请告诉我。 谢谢!

基本上最接近的旋转将始终小于180度,因此如果您的角度大于180,只需从中减去360以获得负角度。 举个例子,如果最终得到300度,减去360得到-60度。

所以要添加到您当前的代码行:

rot = num * gap;

所有你需要的是:

if (rot > 180)
  rot -= 360;

这做了相当无聊的工作:

function diff(x, y) {
    var a = (x * Math.PI / 180) - Math.PI;
    var b = (y * Math.PI / 180) - Math.PI;
    return Math.atan2(Math.sin(b - a), Math.cos(b - a)) * (180 / Math.PI);
}

它返回-180到180,具体取决于哪个旋转最短。

diff(360, 20)
> 19.999999999999993
diff(20, 360)
> -19.999999999999993
diff(0, 160)
> 160
diff(0, 190)
> -170

暂无
暂无

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

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