あなたの説明から、特定のフレームには6つの状態があります。
- 現在のlerpの開始時間
- Lerpタイムスパン
- 現在の方向
- 現在の時刻
- 開始値
- 終了値
これらから、必要な進捗値を計算できます。たとえば、次のようにします。
function progressValue(startTime, lerpSpanSeconds, dir,
currentTime X, Y, dir, currentTime) {
// lerp
return 0.42;
}
requestAnimationFrame の場合、渡す単純なコールバックが必要です。つまり、関数は、実行時に取得できるものを除いて、必要なものをすべて認識している必要があります。ここでは、実行時に現在の時刻を取得し、そこから残りの作業を行う必要があります。
function animableThing() {
var startTime = 7;
var lerpSpanSeconds = 3;
var dir = +1;
var X = 0;
var Y = 1;
var currentTime = GetCurrentUnicornTime();
var thingToAnimate = document.getElementById('myAnimableElement');
var progress = progressValue(startTime, lerpSpanSeconds, dir,
currentTime, X, Y, dir, currentTime);
// reverse when we hit the end
if(progress > Y) {
dir *= -1;
startTime = currentTime;
progress = Y;
}
DrawAnimationThing(thingToAnimate, progress);
// continue the animation
window.requestAnimationFrame(animableThing);
}
しかし、問題があります。スクリプトからの値または画面からの入力、または画面上の要素に関する最新情報を使用してアニメーションを設定できるようにしたい場合はanimableThing
、新しい価値。見よ、母親:
function MotherOfAnimableThings(startTime, lerpSpanSeconds, dir, X, Y,
thingToAnimate)
{
// Passed in variables have scope outside the animableThing, these
// will be private to the animableThing function.
// Consider defaulting or validation here
// Construct a new function freshly each time the Mother is called,
// and return it to the caller. Note that we assign a variable here
// so that we can re-call RequestAnimationFrame to continue the loop
var callback = (function() {
var currentTime = GetCurrentUnicornTime();
var progress = progressValue(startTime, lerpSpanSeconds, dir,
currentTime, X, Y, dir, currentTime);
// reverse when we hit the end
if(progress > Y) {
dir *= -1;
startTime = currentTime;
progress = Y;
}
DrawAnimationThing(thingToAnimate, progress);
window.requestAnimationFrame(callback);
});
return callback;
}
さらに進んで、呼び出し元が呼び出す progressValue 関数、または実際にはコールバックを渡すことで、これを他のタイプのものに一般的にすることができます。これにより、任意の要素、Draw 関数、セットアップ関数を取得してアニメーション化しますが、これは妥当な出発点です。
上記では、Mother を呼び出してanimableThing
関数を作成し、それを使用して RequestAnimationFrame を呼び出すだけです。それ以降は、RequestAnimationFrame を内部的に呼び出してサイクルを継続します。
これで、停止させたいので、チェックできるコールバックに変数を追加して、できるようにします
var animableThing = MotherOfAnimableThings(...);
window.requestAnimationFrame(animableThing);
// ... later
animableThing.stop = true; // it should stop on the next frame