简体   繁体   English

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

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

I'm making a web page that includes a clock with an arrow in the center. 我正在制作一个网页,其中包含一个带箭头的时钟。 When the user clicks on an hour, the arrow rotates to point to what he/she has clicked. 当用户点击一小时时,箭头会旋转以指向他/她点击的内容。

I'm using a jQuery image rotate plugin (jQueryRotate) to rotate the arrow. 我正在使用jQuery图像旋转插件(jQueryRotate)来旋转箭头。

Here is the current code to compute the number of degrees to rotate: 以下是计算要旋转的度数的当前代码:

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;  
}  

When the user clicks one of the hours, it passes num as a value of 1 through 12. 当用户单击其中一个小时时,它会将num作为值1到12传递。

It works fine, but the problem is that if the arrow is pointing to 1 o'clock, and the user clicks 11 o'clock, the arrow rotates clockwise 300 degrees, when it would make more sense to rotate 60 degrees counterclockwise. 它工作正常,但问题是如果箭头指向1点钟,并且用户点击11点钟,箭头顺时针旋转300度,此时逆时针旋转60度会更有意义。

So, how can I write an equation to take the current hour (num) and the hour clicked (sel), and output a value as a positive or negative number, which equals the number of degrees to rotate that is most efficient, rather than just rotate only in one direction? 那么,我怎么能写一个方程来取当前小时(num)和小时点击(sel),并输出一个正数或负数,它等于最有效的旋转度数,而不是只在一个方向旋转?

Any advice is appreciated. 任何建议表示赞赏。 Let me know if you have any questions. 如果您有任何疑问,请告诉我。 Thanks! 谢谢!

Basically the closest rotation will always be less than 180 degrees, so if your angle is greater than 180, just subtract 360 from it to get the negative angle. 基本上最接近的旋转将始终小于180度,因此如果您的角度大于180,只需从中减去360以获得负角度。 Taking your own example, if you end up with 300 degrees, subtract 360 to get -60 degrees. 举个例子,如果最终得到300度,减去360得到-60度。

So to add to your current line of code: 所以要添加到您当前的代码行:

rot = num * gap;

all you need is: 所有你需要的是:

if (rot > 180)
  rot -= 360;

This does the rather boring job: 这做了相当无聊的工作:

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);
}

It returns -180 to 180, depending on which rotation will be the shortest. 它返回-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