css3トランジションを使用して、phonegapを使用してコンパスの動きをスムーズにします。希望の回転を0から359までの角度として計算します。
問題は、たとえば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の値を使用してください。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加