[源码阅读]解析Anime(JS动画库)核心(1)

news/2024/7/3 14:33:05

本次解析将分为2篇文章,当前是第一篇,第二篇在这里

另外,为了能更好的理解这个库,个人写了一个此库的压缩版,实现了核心的功能(主要也是为了更好理解核心功能),内容更少方便阅读,
地址在这里


介绍

anime一个JS轻量动画库,摒弃了常规的left,top属性,全面采用requestAnimateFrame+CSS3属性能充分调用设备进行GPU渲染。

它的亮点有以下(直接引用官网):

  • Keyframes(帧动画): Chain multiple animation properties.
  • Timeline(同步动画): Synchronize multiple instances together.
  • Playback controls(暂停回放功能): Play, pause, restart, seek animations or timelines.
  • CSS transforms(CSS动画): Animate CSS transforms individually.
  • Function based values(函数定义配置(注入了内部属性)): Multiple animated targets can have individual value.
  • SVG Animations(SVG动画): Motion path, line drawing and morphing animations.
  • Easing functions(自定义贝塞尔函数): Use the built in functions or create your own Cubic Bézier curve easing.

这么多亮点,其实关键函数就3~4个。

因为这里都是使用缓动函数算法,也就是通过 初始位置, 结束位置, 持续时间,已消耗的时间 计算出当前所在位置。

初始位置结束位置持续时间是作为参数传入配置的,因此计算已消耗时间就是完成动画的核心。

下面就深入了解下它的核心。

深入理解

先了解几个时间的变量,动画都是算法+时间=位置这么算出来的:

// 记录当前位置所对应的时间,根据lastTime计算
instance.cuurentTime
// 记录当前位置所消耗的时间
engineTime
// 记录上一次计算完毕赋值后的位置对应时间
lastTime
// 上一次调用raf的时间
startTime
// 当前位置所消耗时间(能匹配反转状态),根据engineTime计算
insTime
// 动画持续时间
insDuration
// 延迟时间
delay
// 从什么时间点开始动画
insOffset

接着看几个关键函数,这里先不放具体代码,只是先知道是做什么的(按一个正常动画顺序排放):

// anime的核心机制, 递归调用raf执行(关键)
const engine = (() => {
  // ...requestAnimateFrame
})();

// anime主体
function anime(params){
  
  // 定义instance 也是最终返回值
  let instance = createNewInstance(params);
  
  // 外部API 从当前位置开始执行动画
  instance.play = function() {}
  
  // 配置 startTime 和 engineTime(关键)
   instance.tick = function(t) {}
   
  // 对当前engineTime进行判断,确定动画方案(关键)
  function setInstanceProgress(engineTime) {}
  
  // 计算动画当前位置 并且赋值(关键)
  function setAnimationsProgress(insTime){}

  // 直接跳到参数time的时间所在的位置
  instance.seek = function(time) {}
  // 外部API 暂停
  instance.pause = function() {}
  // 外部API 反转
  instance.reverse = function() {}
  // 外部API reset
  instance.reset = function() {}
  // 外部API 重新开始
  instance.restart = function() {}
  /*...*/
  return instance
}

关键函数就4个,其他都是一些对关键函数的具体使用

接着一个个解析:

  • createNewInstance

其实就是对属性和方法合并成一个整体对象,这个对象是贯穿全局的,因此里面什么都有...

 function createNewInstance(params) {
  
    /* 对params进行处理 */
    const instanceSettings = replaceObjectProps(defaultInstanceSettings, params);
    const tweenSettings = replaceObjectProps(defaultTweenSettings, params);
    const animatables = getAnimatables(params.targets);
    const properties = getProperties(instanceSettings, tweenSettings, params);
    const animations = getAnimations(animatables, properties);
        
    // mergeObjects(o1,o2)相当于 Object.assing({},o2,o1)
    return mergeObjects(instanceSettings, {
      children: [],
      animatables: animatables,
      animations: animations,
      duration: getInstanceTimings('duration', animations, instanceSettings, tweenSettings),
      delay: getInstanceTimings('delay', animations, instanceSettings, tweenSettings)
    });
  }
  • instance.play

此处先做了防护,只有paused状态下才会执行,lastTime这里是调取当前动画的位置对应的时间,因此才可以实现从任意位置开始动画。

 // 外部API 从当前位置开始执行动画
instance.play = function() {
  if (!instance.paused) return;
  instance.paused = false;
  // 从0 开始
  startTime = 0;
  // 调取当前动画当前位置所对应的时间
  lastTime = adjustTime(instance.currentTime);
  // 给 activeInstances 添加当前实例,说明这是一个正在运行的动画
  activeInstances.push(instance);
  // raf未启动,调用engine
  if (!raf) engine();
}
  • engine

anime的核心机制,通过递归调用requestAnimateFrame,当检测到需要执行动画的集合activeInstances有值,调用instance.tick。

  // IIFE 之后调用engine相当于执行内部的play
  const engine = (() => {
    // step收到一个参数,
    function play() { raf = requestAnimationFrame(step); };
    // 这里的参数t是 raf的参数中可以接受的一个时间戳,表示触发调用的时间
    function step(t) {
      // activeInstances指正在被执行的动画集合
      const activeLength = activeInstances.length;
      // 存在正在运行的动画
      if (activeLength) {
        let i = 0;
        while (i < activeLength) {
          // 调用tick执行
          if (activeInstances[i]) activeInstances[i].tick(t);
          i++;
        }
        play();
      } else {
        // 不存在正在运行的动画 cancel
        cancelAnimationFrame(raf);
        raf = 0;
      }
    }
    return play;
  })();
  • instance.tick

tick的作用通过参数traf的一个时间戳概念,计算出距离上一次调用实际消耗的时间engineTime

例如:上一次调用时间戳是1000,也就是1秒,中途突然执行一个巨大的任务,等任务结束,时间戳是20000
那么这次的engineTime就是lastTime+20000-1000,也就是计算这次动画从上次位置再加上19秒的位置...
那么anime对于这种情况是怎么处理呢?继续看下一个setInstanceProgress

// 配置 startTime 和 engineTime
instance.tick = function(t) {
  now = t;
  // startTime 如果首次执行 就是now,否则就是上一次tick的时间
  if (!startTime) startTime = now;
  // lastTime 是上一次执行结束后动画对应位置的时间戳
  // engineTime 是到动画目前为止消耗的总时间,一般理论上讲是lastTime+16.6667
  const engineTime = (lastTime + now - startTime) * anime.speed;
  setInstanceProgress(engineTime);
}
  • setInstanceProgress

这个函数接受一个消耗的时间值,在内部对其进行适配和定义了各种情况的动画起始点,传递给setAnimationsProgress

例如,上面那个例子,如果消耗了19秒,就如进入这个判断:从结束点开始动画(考虑reverse的情况)。

// 消耗的时间超出了持续时间 并且当前位置不在终点  或者 未设定持续时间
if ((insTime >= insDuration && insCurrentTime !== insDuration) || !insDuration){
  if ((insTime >= insDuration && insCurrentTime !== insDuration) || !insDuration) {
    // 从结束点开始
    setAnimationsProgress(insDuration);
    if (!insReversed) countIteration();
  }
}

setInstanceProgress(省略了一些配置的定义)

// 对当前engineTime进行判断,确定动画方案
function setInstanceProgress(engineTime) {
  // 动画持续时间
  const insDuration = instance.duration;
  // 从什么时间点开始动画
  const insOffset = instance.offset;
  // 加上延迟后的开始时间
  const insStart = insOffset + instance.delay;
  // 记录当前位置所对应的时间
  const insCurrentTime = instance.currentTime;
  // 是否是反转状态
  const insReversed = instance.reversed;
  // 当前位置所消耗时间(能匹配反转状态)
  // 这里adjustTime就是如果是反转状态,则返回 insDuration-engineTime
  const insTime = adjustTime(engineTime);
  /* ... */
  // 消耗的时间大于应该开始的时间 并且 消耗的时间在持续时间范围内
  if (insTime > insOffset && insTime < insDuration) {
    setAnimationsProgress(insTime);
  } else {
    // 消耗的时间小于应该开始的时间 并且 当前位置不在起点
    if (insTime <= insOffset && insCurrentTime !== 0) {
      // 从头开始
      setAnimationsProgress(0);
      if (insReversed) countIteration();
    }
    // 消耗的时间超出了持续时间 并且当前位置不在终点  或者 未设定持续时间
    if ((insTime >= insDuration && insCurrentTime !== insDuration) || !insDuration) {
      // 从结束点开始
      setAnimationsProgress(insDuration);
      if (!insReversed) countIteration();
    }
  }
  setCallback('update');
  // 消耗时间大于持续时间 并且在终点(不在终点的上面已经判断了)
  if (engineTime >= insDuration) {
    if (instance.remaining) {
      startTime = now;
      if (instance.direction === 'alternate') toggleInstanceDirection();
      // remaining为false,remaining>0说明还需要继续动画
    } else {
      // 完成动画的执行
      instance.pause();
      if (!instance.completed) {
        instance.completed = true;
        setCallback('complete');
        if ('Promise' in window) {
          resolve();
          promise = makePromise();
        }
      }
    }
    lastTime = 0;
  }
}

关键函数setAnimationsProgress和后续的操作函数都放在下一篇继续解析。


http://www.niftyadmin.cn/n/2205210.html

相关文章

微信小程序--手写一个地区选择器(多级联动)

前言 通过微信小程序官方文档&#xff0c;我们可以看到表单组件中有picker这类滚动选择器。 现支持五种选择器&#xff0c;通过mode来区分&#xff0c;默认是普通选择器。 普通选择器多列选择器时间选择器日期选择器省市区选择器需求场景&#xff1a;官方的地区选择器是三级联动…

HTML和CSS属性的正确书写规范

网页的重要性评级&#xff1a; 网页的排名。标签的语义化&#xff0c;正确的标签做正确的事情。提升网页的加载速度。1. CSS代码优化&#xff0c;代码的正确排列顺序&#xff0c;不正确的代码会导致浏览器解析代码回流&#xff0c;会拖慢浏览器的加载速度。 减少图片服务器的请…

Redis进阶实践之十六 Redis大批量增加数据

2019独角兽企业重金招聘Python工程师标准>>> Redis进阶实践之十六 Redis大批量增加数据 一、介绍 有时候&#xff0c;Redis实例需要在很短的时间内加载大量先前存在或用户生成的数据&#xff0c;以便尽可能快地创建数百万个键。这就是所谓的批量插入&…

LINUX-centos7tomcat安装教程

1.yum install -y tomcat (jdk&#xff0c;依赖自动给装好了&#xff09;2.systemctl start tomcat(打开tomcat&#xff09;3.ps -aux | grep tomcat(查询是否打开&#xff09;4.systemctl stop firewalld.service&#xff08;关闭防火墙&#xff09;5.systemctl disable firew…

动画效果

显示动画 方式一&#xff1a; $("div").show(); 解释&#xff1a;无参数&#xff0c;表示让指定的元素显示出来。其实这个方法的底层就是通过display&#xff1a;block&#xff1b;实现 方式二&#xff1a; $("div").show(3000); 解释&#xff1a;通过控制…

FFmpeg 拉取rtsp 做hls切片

2019独角兽企业重金招聘Python工程师标准>>> ./ffmpeg -i rtsp://184.72.239.149/vod/mp4:BigBuckBunny_115k.mov -fflags flush_packets -max_delay 1 -an -flags -global_header -hls_time 1 -hls_list_size 3 -hls_flags delete_segmentsomit_endlist -vcodec co…

路透社:欧盟将无条件批准微软 75 亿美元收购 GitHub

北京时间10月8日晚间消息&#xff0c;路透社今日援引两位知情人士的消息称&#xff0c;欧盟将无条件批准微软 75 亿美元收购 GitHub 的交易。GitHub 是全球领先的代码托管平台&#xff0c;拥有 2800 多万开发者用户。微软今年6月宣布&#xff0c;将以价值 75 亿美元的股票收购 …

Dell 14G服务器通过BIOS配置RAID

1.开机&#xff0c;根据界面提示按<F2>进入<System Setup>管理界面&#xff1b;2.选择<Device Settings>&#xff1b;3.选择<Dell PERC<PERC H730P Adapter>Configuration Utility>&#xff1b;4.选择<Configuration Management>&#xff…