gpt4 book ai didi

css3 旋转过渡,不走最短路径

转载 作者:技术小花猫 更新时间:2023-10-29 11:45:58 25 4
gpt4 key购买 nike

我想使用 css3 过渡来平滑使用 phonegap 的罗盘移动。我将所需的旋转计算为从 0 到 359 的 Angular 。

问题是,当它应该从例如 359 变为 0 时,它不会顺时针旋转 1 度,而是逆时针旋转 359 度。

有没有办法告诉 css 总是采用最短的方式进行旋转?

最佳答案

转换完全按照您的指示进行。

它从 359 度开始到 1 度。您希望将 360 度“翻转”回 1 度,这实际上是 361 度。变换过渡的工作方式是在值之间进行插值。

您的问题的解决方案是创建一个包含旋转度数的计数器变量:

var rot = 0;  // lets start at zero, you can apply whatever later

要应用旋转,更改值:

rot = 359;
// note the extra brackets to ensure the expression is evaluated before
// the string is assigned this is require in some browsers
element.style.transform = ("rotate( " + rot + "deg )");

所以如果你这样做:

rot = 1;
element.style.transform = ("rotate( " + rot + "deg )");

它回去了。所以你需要看看它是否更接近 360 或 0,无论它已经旋转了多少次。为此,您可以检查 element.style.transform 的值,它只是当前的 rot 值,然后与新的 rot 值进行比较。但是,您需要根据可能存在的旋转次数来执行此操作,因此:

var apparentRot = rot % 360;

现在无论它旋转了多少次,你都知道它绕了多远,负值等于值 + 360:

if ( apparentRot < 0 ) { apparentRot += 360; } 

现在您已经对任何负值进行了归一化,可以询问是否需要正旋转(在您的情况下为 360 度)或负旋转。由于您似乎将新的旋转值指定为 0-360 度,因此这简化了您的问题。您可以询问新旋转 + 360 是否比新旋转本身更接近旧值:

var aR,          // what the current rotation appears to be (apparentRot shortened)
nR, // the new rotation desired (newRot)
rot; // what the current rotation is and thus the 'counter'

// there are two interesting events where you have to rotate through 0/360
// the first is when the original rotation is less than 180 and the new one
// is greater than 180deg larger, then we go through the apparent 0 to 359...
if ( aR < 180 && (nR > (aR + 180)) ) {
// rotate back
rot -= 360;
}

// the second case is when the original rotation is over 180deg and the new
// rotation is less than 180deg smaller
if ( aR >= 180 && (nR <= (aR - 180)) ) {
// rotate forward
rot += 360;
}

除此之外,只需将新旋转的值添加到 rot 即可:

rot += (nR - aR); //  if the apparent rotation is bigger, then the difference is
// 'negatively' added to the counter, so the counter is
// correctly kept, same for nR being larger, the difference is
// added to the counter

清理一下:

var el, rot;

function rotateThis(element, nR) {
var aR;
rot = rot || 0; // if rot undefined or 0, make 0, else rot
aR = rot % 360;
if ( aR < 0 ) { aR += 360; }
if ( aR < 180 && (nR > (aR + 180)) ) { rot -= 360; }
if ( aR >= 180 && (nR <= (aR - 180)) ) { rot += 360; }
rot += (nR - aR);
element.style.transform = ("rotate( " + rot + "deg )");
}

// this is how to intialize and apply 0
el = document.getElementById("elementYouWantToUse");
rotateThis(el, 0);

// now call function
rotateThis(el, 359);
rotateThis(el, 1);

计数器可以是正数也可以是负数,没关系,只需使用 0-359 之间的值进行新的轮换。

关于css3 旋转过渡,不走最短路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19618745/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com