rxjs-create-tween
Version:
Create observables that sample from easing functions on animation frames
47 lines (44 loc) • 1.83 kB
JavaScript
import { Observable } from "rxjs/_esm5"; // eslint-disable-line
/**
* Creates an observable that emits samples from an easing function on every animation frame
* for a duration `d` ms.
*
* The first value will be emitted on the next animation frame,
* and is the value of the easing function at `t = 0`.
* The final value is guaranteed to be the easing function at `t = d`.
* The observable completes one frame after the final value was emitted.
*
* @param {function(t: number, b: number, c: number, d: number, [s]: number): number} easingFunction
* - the easing fuction to sample from; can use any of Robert Penner's easing functions
(without the `x` paramter)
* @param {number} b - beginning value and 2nd parameter of the easing function
* @param {number} c - change in value (or end value) and 3rd parameter of the easing function
* @param {number} d - total duration of the tween in ms and 4th parameter of the easing function
* @param {number} [s] - 5th parameter of the easing function (optional)
* @return {Observable<number>} - an observable emitting samples of the easing function on
* animation frames for `d` ms.
*/
export function createTween(easingFunction, b, c, d, s) {
return Observable.create(function(observer) {
let startTime;
let id = requestAnimationFrame(function sample(time) {
startTime = startTime || time;
const t = time - startTime;
if (t < d) {
observer.next(easingFunction(t, b, c, d, s));
id = requestAnimationFrame(sample);
} else {
observer.next(easingFunction(d, b, c, d, s));
id = requestAnimationFrame(function() {
return observer.complete();
});
}
});
return function() {
if (id) {
cancelAnimationFrame(id);
}
};
});
}
export default createTween;