PHP前端开发

增强您的 Web 动画:像专业人士一样优化 requestAnimationFrame

百变鹏仔 3天前 #JavaScript
文章标签 您的

流畅且高性能的动画在现代 web 应用程序中至关重要。然而,管理不当可能会使浏览器的主线程过载,导致性能不佳和动画卡顿。 requestanimationframe (raf) 是一种浏览器 api,旨在将动画与显示器的刷新率同步,确保与 settimeout 等替代方案相比更流畅的运动。但高效使用 raf 需要仔细规划,尤其是在处理多个动画时。

在本文中,我们将探讨如何通过集中动画管理、引入 fps 控制以及保持浏览器主线程响应来优化 requestanimationframe。


了解 fps 及其重要性

在讨论动画性能时,每秒帧数 (fps) 至关重要。大多数屏幕以 60 fps 刷新,这意味着 requestanimationframe 每秒被调用 60 次。为了保持流畅的动画,浏览器必须在每帧约 16.67 毫秒内完成其工作。

如果在单个帧中运行太多任务,浏览器可能会错过其目标帧时间,从而导致卡顿或丢帧。降低某些动画的 fps 有助于减少主线程的负载,从而在性能和流畅度之间取得平衡。

具有 fps 控制功能的集中式动画管理器可实现更好的性能

为了更有效地管理动画,我们可以通过共享循环集中处理动画,而不是在代码中分散多个 requestanimationframe 调用。集中式方法可最大程度地减少冗余调用,并更轻松地添加 fps 控制。

下面的animationmanager类允许我们在控制目标fps的同时注册和取消注册动画任务。默认情况下,我们的目标是 60 fps,但这可以根据性能需求进行调整。

class animationmanager {  private tasks: set<framerequestcallback> = new set();  private fps: number = 60; // target fps  private lastframetime: number = performance.now();  private animationid: number | null = null; // store the animation frame id  private run = (currenttime: number) =&gt; {    const deltatime = currenttime - this.lastframetime;    // ensure the tasks only run if enough time has passed to meet the target fps    if (deltatime &gt; 1000 / this.fps) {      this.tasks.foreach((task) =&gt; task(currenttime));      this.lastframetime = currenttime;    }    this.animationid = requestanimationframe(this.run);  };  public registertask(task: framerequestcallback) {    this.tasks.add(task);    if (this.tasks.size === 1) {      this.animationid = requestanimationframe(this.run); // start the loop if this is the first task    }  }  public unregistertask(task: framerequestcallback) {    this.tasks.delete(task);    if (this.tasks.size === 0 &amp;&amp; this.animationid !== null) {      cancelanimationframe(this.animationid); // stop the loop if no tasks remain      this.animationid = null; // reset the id    }  }}export const animationmanager = new animationmanager();</framerequestcallback>

在此设置中,我们计算帧之间的 deltatime,以确定基于目标 fps 是否已经过去了足够的时间进行下一次更新。这使我们能够限制更新频率,以确保浏览器的主线程不会过载。


实际示例:为具有不同属性的多个元素设置动画

让我们创建一个示例,为三个盒子设置动画,每个盒子都有不同的动画:一个缩放,另一个改变颜色,第三个旋转。

这是 html:

<div id="animate-box-1" class="animated-box"></div><div id="animate-box-2" class="animated-box"></div><div id="animate-box-3" class="animated-box"></div>

这是 css:

.animated-box {  width: 100px;  height: 100px;  background-color: #3498db;  transition: transform 0.1s ease;}

现在,我们将添加 javascript 来为每个具有不同属性的框设置动画。一个会缩放,另一个会改变颜色,第三个会旋转。

第 1 步:添加线性插值 (lerp)

线性插值 (lerp) 是动画中常用的技术,用于在两个值之间平滑过渡。它有助于创建渐进且平滑的进程,使其成为随时间推移缩放、移动或更改属性的理想选择。该函数采用三个参数:起始值、结束值和标准化时间 (t),该时间确定过渡的距离。

function lerp(start: number, end: number, t: number): number {  return start + (end - start) * t;}

第 2 步:缩放动画

我们首先创建一个函数来为第一个框的缩放设置动画:

function animatescale(  scalebox: htmldivelement,  startscale: number,  endscale: number,  speed: number) {  let scalet = 0;  function scale() {    scalet += speed;    if (scalet &gt; 1) scalet = 1;    const currentscale = lerp(startscale, endscale, scalet);    scalebox.style.transform = `scale(${currentscale})`;    if (scalet === 1) {      animationmanager.unregistertask(scale);    }  }  animationmanager.registertask(scale);}

第 3 步:彩色动画

接下来,我们为第二个框的颜色变化设置动画:

function animatecolor(  colorbox: htmldivelement,  startcolor: number,  endcolor: number,  speed: number) {  let colort = 0;  function color() {    colort += speed;    if (colort &gt; 1) colort = 1;    const currentcolor = math.floor(lerp(startcolor, endcolor, colort));    colorbox.style.backgroundcolor = `rgb(${currentcolor}, 100, 100)`;    if (colort === 1) {      animationmanager.unregistertask(color);    }  }  animationmanager.registertask(color);}

第 4 步:旋转动画

最后,我们创建旋转第三个框的函数:

function animaterotation(  rotatebox: htmldivelement,  startrotation: number,  endrotation: number,  speed: number) {  let rotationt = 0;  function rotate() {    rotationt += speed; // increment progress    if (rotationt &gt; 1) rotationt = 1;    const currentrotation = lerp(startrotation, endrotation, rotationt);    rotatebox.style.transform = `rotate(${currentrotation}deg)`;    // unregister task once the animation completes    if (rotationt === 1) {      animationmanager.unregistertask(rotate);    }  }  animationmanager.registertask(rotate);}

第 5 步:开始动画

最后,我们可以启动所有三个盒子的动画:

// Selecting the elementsconst scaleBox = document.querySelector("#animate-box-1") as HTMLDivElement;const colorBox = document.querySelector("#animate-box-2") as HTMLDivElement;const rotateBox = document.querySelector("#animate-box-3") as HTMLDivElement;// Starting the animationsanimateScale(scaleBox, 1, 1.5, 0.02); // Scaling animationanimateColor(colorBox, 0, 255, 0.01); // Color change animationanimateRotation(rotateBox, 360, 1, 0.005); // Rotation animation

主线程注意事项

使用 requestanimationframe 时,必须记住动画在浏览器的主线程上运行。主线程超载过多的任务可能会导致浏览器错过动画帧,从而导致卡顿。这就是为什么使用集中式动画管理器和 fps 控制等工具优化动画可以帮助保持流畅度,即使有多个动画也是如此。


结论

在 javascript 中有效管理动画需要的不仅仅是使用 requestanimationframe。通过集中动画并控制 fps,您可以确保动画更流畅、性能更高,同时保持主线程响应能力。在此示例中,我们展示了如何使用单个 animationmanager 处理多个动画,演示如何优化性能和可用性。虽然为了简单起见,我们专注于保持一致的 fps,但这种方法可以扩展到处理各种动画的不同 fps 值,尽管这超出了本文的范围。

github 存储库: https://github.com/jbassx/raf-optimization
stackblitz: https://stackblitz.com/~/github.com/jbassx/raf-optimization

领英: https://www.linkedin.com/in/josephciullo/