代码实现tween补间

使用:


    this.flatTween = new TweenAnimation({
      start,
      end,
      duration: this.scannerDuration * 1000, // 动画持续时间:3 秒
      onUpdate: (points) => setPoints(points),
      repeat: Infinity, // 无限循环
    });

基类

class TweenAnimation {
  constructor({ start, end, duration, onUpdate, repeat = Infinity }) {
    this.start = start; // 初始值
    this.end = end; // 结束值
    this.duration = duration; // 动画持续时间(毫秒)
    this.onUpdate = onUpdate; // 更新回调
    this.repeat = repeat; // 重复次数,Infinity 表示无限
    this.startTime = false; // 动画开始时间
    this.elapsed = 0; // 累计经过的时间
    this.isRunning = true; // 是否运行中
    // console.log(start, end, duration, onUpdate, (repeat = Infinity));
  }

  update(deltaTime) {
    if (!this.isRunning) return;
    // 累计时间
    this.elapsed += deltaTime;
    let progress = this.elapsed / this.duration;

    // 限制进度在 [0, 1] 范围内
    if (progress > 1) progress = 1;

    // 线性插值计算当前值
    const current = {};
    for (const key in this.start) {
      current[key] = this.start[key] + (this.end[key] - this.start[key]) * progress;
    }

    // 调用更新回调
    if (this.onUpdate) this.onUpdate(current);

    // 动画结束检测
    if (progress >= 1) {
      if (this.repeat === Infinity || this.repeat > 0) {
        this.elapsed = 0; // 重置动画时间
        if (this.repeat !== Infinity) this.repeat--;
      } else {
        this.isRunning = false; // 停止动画
      }
    }
  }

  stop() {
    this.isRunning = false; // 停止动画
  }

  startFunc() {
    this.isRunning = true; // 启动动画
    this.elapsed = 0; // 重置时间
  }
}

 

posted @ 2025-05-08 14:04  SimoonJia  阅读(23)  评论(0)    收藏  举报