tween.ts 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import { Easing, Tween } from "@tweenjs/tween.js";
  2. import { cancelAnimationFrame, requestAnimationFrame } from "@tarojs/runtime";
  3. export interface TweenHandlerOptions<T extends object> {
  4. /** 当前属性 */
  5. curProps: T;
  6. /** 目标属性 */
  7. targetProps: T;
  8. /** 动画更新回调 */
  9. onUpdate?: (e: T) => void;
  10. /** 动画完成回调 */
  11. cb?: Function;
  12. /** 动画时长 默认 1000 ms */
  13. delay?: number;
  14. easing?: any;
  15. }
  16. export function tweenHandler<T extends object>(
  17. options: TweenHandlerOptions<T>
  18. ) {
  19. let animaId: number | NodeJS.Timeout = 0;
  20. const { curProps, targetProps, onUpdate, cb } = options;
  21. const tween = new Tween(curProps)
  22. .to(targetProps, typeof options.delay === "number" ? options.delay : 1000)
  23. .onUpdate(onUpdate)
  24. .onComplete(() => {
  25. cancelAnimationFrame(animaId as number);
  26. cb && cb();
  27. })
  28. .easing(options.easing || Easing.Quintic.Out)
  29. .start();
  30. function animate(time?: number) {
  31. animaId = requestAnimationFrame(animate);
  32. tween.update(time);
  33. }
  34. animate();
  35. return tween;
  36. }