js/ts金额由大到小动画实现

// js写法
function animation(duration, from, to, onProgress) {
    const startTime = Date.now();
   
    function _run() {
        const elapsed = Date.now() - startTime; // 已过去的时间
        const progress = Math.min(elapsed / duration, 1); // 进度(0-1)
       
        // 计算当前值
        const currentValue = from + (to - from) * progress;
       
        // 触发回调
        if (onProgress) {
            // 回调传递数字
            onProgress(currentValue);
        }
       
        if (progress < 1) {
            // 继续动画
            requestAnimationFrame(_run); return;
        }
        // 动画结束,确保最终值精确
        if (onProgress) onProgress(to);
    }
    _run();
}

// 调用
animation(1000, 0, 100, (value) => {
    // 时间毫秒:1000
    // 0: 开始值
    // 100:结束值
    // value:回调函数
    console.log('当前值', value.toFixed(2));
});


// 定义动画参数接口
interface AnimationOptions {
  /** 动画总时长(毫秒) */
  duration: number;
  /** 起始值 */
  from: number;
  /** 结束值 */
  to: number;
  /** 动画过程中每一帧的回调,接收当前值 */
  onProgress: (value: number) => void;
  /** 动画结束时的回调(可选) */
  onComplete?: () => void;
}

/**
 * 执行一个数值动画
 * @param options 动画配置对象
 */
function animationTS(options: AnimationOptions): void {
  const { duration, from, to, onProgress, onComplete, easing } = options;
  const startTime = Date.now();


  function _run(): void {
    const elapsed = Date.now() - startTime;
    // 计算进度(0到1),并用clamp确保不超过1
    const rawProgress = elapsed / duration;
    const progress = Math.min(rawProgress, 1);

    // 核心计算:根据缓动后的进度计算当前值
    const currentValue = from + (to - from) * progress;

    // 触发进度回调
    onProgress(currentValue);

    if (progress < 1) {
      // 继续动画
      requestAnimationFrame(_run);
    } else {
      // 动画结束,确保最终值精确等于 `to`
      onProgress(to);
      onComplete?.(); // 可选链操作符调用完成回调
    }
  }

  _run();
}

// 基本使用
animationTS({
  duration: 1500,
  from: 599.00,
  to: 59.90,
  onProgress: (value: number) => {
    // 在回调中按需格式化显示
    console.log(`当前金额: ${value.toFixed(2)}`);
    // 更新UI,例如:
    // document.getElementById('price').textContent = value.toFixed(2);
  },
  onComplete: () => {
    console.log('✅ 金额变化动画完成!');
  }
});
posted @ 2025-12-21 00:11  37点2度  阅读(9)  评论(0)    收藏  举报