我想使用css3過渡來使用phonegap平滑指南針運動。我計算所需的旋轉角度從0到359.css3旋轉過渡,不採用最短路線
問題是,當它應該從例如359變爲0時,它不會順時針轉1度,而是逆時針轉359度。
有沒有辦法告訴css總是採取最短的方式進行輪換?
我想使用css3過渡來使用phonegap平滑指南針運動。我計算所需的旋轉角度從0到359.css3旋轉過渡,不採用最短路線
問題是,當它應該從例如359變爲0時,它不會順時針轉1度,而是逆時針轉359度。
有沒有辦法告訴css總是採取最短的方式進行輪換?
這個轉換正在完成你所說的。
它從359deg開始,進入1deg。你正在尋找'翻轉'360deg回到1deg,這真的是361deg。變換轉換的工作方式是在值之間進行插值。
你的問題的解決方案是使持有度旋轉計數器變量:
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; }
現在你已經歸任何負值,並且可以(在你的情況下,通過360deg)詢問是否正轉或負是必要的。由於您似乎將新的旋轉值設置爲0-360deg,因此這可以簡化您的問題。你可以問,如果新的旋轉+ 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之間的值。
看看你是否可以使用負數。從-1deg到0deg是順時針的,從359deg到0deg是逆時針。
除了aR> = 0嗎? :aR + = 360;是無效的語法,你需要寫aR> = 0? null:aR + = 360;或者無論如何,這是解決方案 – elbarto132
感謝您捕捉錯誤。我不知道三元運算符。我已經改變了它,因爲它不是必需的。 – thisiate
建議讓代碼更加清晰簡明:在規範化aR之後,計算旋轉的差異「drot = nR - aR;'然後你可以簡單地做'if(drot> 180){drot - = 360 }'和'if(drot <180){drot + = 360}'最後'rot + = drot' – user3502079