UNPKG

ts-useful

Version:

Functions for animation, color transitions, ecliptic, bezier, decasteljau, curves, three dimensional curves, smooth scrolling, random range, randomItem, mobius index, vectors, physics vectors, and easing.

54 lines 1.85 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Animate = void 0; /** * * @param action (pct: number) => void * @param options { fps?: number, duration?: number, resumePct?: number, stop?: () => boolean, cb?: () => void } */ const Animate = async (action, options) => { const { stop, cb } = options ? options : { stop: undefined, cb: undefined }; let { duration, fps, resumePct } = options ? options : { duration: undefined, fps: undefined, resumePct: undefined }; duration ?? (duration = 1000); fps ?? (fps = 60); if (resumePct) { duration *= resumePct; } const frameRate = duration / fps; const start = performance.now(); const endTime = start + duration; const diff = endTime - start; const nextFrame = () => new Promise(res => { return window.requestAnimationFrame(res); }); let frameCheck = start; async function AnimateFrame() { const stp = stop ? await stop() : undefined; if (stp) { return; } const now = performance.now(); const timePast = now - start; const elapsed = now - frameCheck; if (elapsed > frameRate) { frameCheck = now - (elapsed % frameRate); const pct = Math.max(0, Math.min(1, (resumePct === 1 ? undefined : resumePct) ?? (timePast / diff))); if (resumePct) { resumePct = undefined; } ; await action(pct); } if (now < endTime) { await nextFrame(); await AnimateFrame(); } else { if (cb) await cb(); } } ; await nextFrame(); await AnimateFrame(); }; exports.Animate = Animate; //# sourceMappingURL=animate.js.map