requestAnimationFrame动画实现教程
时间:2025-08-04 10:21:27 195浏览 收藏
本篇文章主要是结合我之前面试的各种经历和实战开发中遇到的问题解决经验整理的,希望这篇《requestAnimationFrame 动画序列实现教程》对你有很大帮助!欢迎收藏,分享给更多的需要的朋友学习~
本文介绍如何使用 requestAnimationFrame 实现动画效果的序列播放,解决多个动画同时执行的问题。通过自定义的 animateInterpolationSequence 函数,可以灵活地定义动画序列,控制动画的起始值、持续时间、缓动函数等,从而实现复杂的动画效果。文章包含详细的代码示例,展示如何使用该函数创建淡入淡出、闪烁等动画效果。
动画序列的实现
requestAnimationFrame 是一个浏览器 API,用于在浏览器准备好重新绘制屏幕时,通知开发者更新动画。它接受一个回调函数作为参数,该回调函数会在下一次重绘之前执行。通过 requestAnimationFrame,可以创建平滑流畅的动画效果。
然而,如果直接连续调用多个 requestAnimationFrame,它们的回调函数会几乎同时执行,导致动画效果重叠。为了解决这个问题,我们需要一种机制来控制动画的执行顺序,确保它们按照预定的顺序播放。
animateInterpolationSequence 函数
以下是一个通用的函数,可以处理任意过渡序列:
function animateInterpolationSequence (callback, ...sequence) { if (sequence.length == 0) { return null; } // this script supports 10 microseconds of precision without rounding errors let animationTimeStart = Math.floor(performance.now() * 100); let timeStart = animationTimeStart; let duration = 0; let easing; let valueStart; let valueEnd = sequence[0].start; let nextId = 0; let looped = (typeof sequence[sequence.length - 1].end != 'number'); let alive = true; let rafRequestId = null; // callback of requestAnimationFrame function update (time) { time = (rafRequestId == null) ? animationTimeStart : Math.floor(time * 100); // iterate over finished sequence items while (time - timeStart >= duration) { if (sequence.length > nextId) { // proceed to the next item let currentItem = sequence[nextId++]; let action = (sequence.length > nextId) ? 'continue': (looped) ? 'looping' : 'finishing'; if (action == 'looping') { nextId = 0; } timeStart += duration; duration = Math.floor(currentItem.duration * 100); easing = (typeof currentItem.easing == 'function')? currentItem.easing: null; valueStart = valueEnd; valueEnd = (action == 'finishing')? currentItem.end: sequence[nextId].start; } else { // the animation is finished safeCall(() => callback((time - animationTimeStart) / 100, valueEnd, true)); return; } } // interpolation math let x = (time - timeStart) / duration; if (easing) { x = safeCall(() => easing(x), x); } let value = valueStart + (valueEnd - valueStart) * x; // continue the animation safeCall(() => callback((time - animationTimeStart) / 100, value, false)); if (alive) { rafRequestId = window.requestAnimationFrame(update); } } // exceptions are our friends // if they have to say something, we'll give them the opportunity function safeCall (callback, defaultResult) { try { return callback(); } catch (e) { window.setTimeout(() => { throw e; }); return defaultResult; } } update(); return function stopAnimation () { window.cancelAnimationFrame(rafRequestId); alive = false; }; }
这个函数接受一个回调函数 callback 和一个动画序列 sequence 作为参数。callback 函数会在每一帧被调用,用于更新动画效果。sequence 是一个数组,包含一系列动画片段的描述。
每个动画片段是一个对象,包含以下属性:
- start: 动画的起始值。
- duration: 动画的持续时间(毫秒)。
- end (可选): 动画的结束值。 如果没有提供end,则认为动画是循环的。
- easing (可选): 缓动函数,用于控制动画的速度变化。
animateInterpolationSequence 函数内部使用 requestAnimationFrame 来驱动动画,并根据 sequence 中的描述,依次执行每个动画片段。
使用示例
以下是一个使用 animateInterpolationSequence 函数实现星形动画的示例:
function renderStar (alpha, rotation, corners, density) { let canvas = document.getElementById('canvas'); let ctx = canvas.getContext('2d'); ctx.save(); // erase ctx.clearRect(0, 0, canvas.width, canvas.height); // draw checkerboard ctx.fillStyle = 'rgba(0, 0, 0, .2)'; let gridSize = 20; for (let y = 0; y * gridSize < canvas.height; y++) { for (let x = 0; x * gridSize < canvas.width; x++) { if ((y + x + 1) & 1) { ctx.fillRect(x * gridSize, y * gridSize, gridSize, gridSize); } } } // star: geometry math let centerX = canvas.width / 2; let centerY = canvas.height / 2; let radius = Math.min(centerX, centerY) * 0.9; function getCornerCoords (corner) { let angle = rotation + (Math.PI * 2 * corner / corners); return [ centerX + Math.cos(angle) * radius, centerY + Math.sin(angle) * radius ]; } // star: build path ctx.beginPath(); ctx.moveTo(...getCornerCoords(0)); for (let i = density; i != 0; i = (i + density) % corners) { ctx.lineTo(...getCornerCoords(i)); } ctx.closePath(); // star: draw ctx.shadowColor = 'rgba(0, 0, 0, .5)'; ctx.shadowOffsetX = 6; ctx.shadowOffsetY = 4; ctx.shadowBlur = 5; ctx.fillStyle = `rgba(255, 220, 100, ${alpha})`; ctx.fill(); ctx.restore(); } // quintic easing function easeOutQuint (x) { return 1 - Math.pow(1 - x, 5); } // the demo animateInterpolationSequence( (time, value, finished) => { renderStar(value, Date.now() / 1000, 5, 2); }, { start: 1, duration: 2000 }, // 0 to 2 sec: opaque { start: 1, duration: 500 }, // 2 to 3 sec: linear fade-out + fade-in { start: 0, duration: 500 }, { start: 1, duration: 500 }, // 3 to 4 sec: again { start: 0, duration: 500 }, { start: 1, duration: 2000 }, // 4 to 6 sec: opaque { start: 1, duration: 500, // 6 to 7 sec: fade-out + fade-in easing: easeOutQuint }, // with custom easing { start: 0, duration: 500, easing: easeOutQuint }, { start: 1, duration: 500, // 7 to 8 sec: again easing: easeOutQuint }, { start: 0, duration: 500, easing: easeOutQuint }, { start: 1, duration: 2000 }, // 8 to 10 sec: opaque { start: 1, duration: 0 }, // instant switch ahead ...((delay, times) => { // 10 to 11 sec: flicker let items = [ { start: .75, duration: delay }, // wait { start: .75, duration: 0 }, // instant switch .75 -> .25 { start: .25, duration: delay }, // wait { start: .25, duration: 0 } // instant switch .25 -> .75 ]; while (--times) { items.push(items[0], items[1], items[2], items[3]); } return items; })(50, 20) );
在这个示例中,renderStar 函数用于绘制星形。animateInterpolationSequence 函数被用来控制星形的透明度变化,实现淡入淡出、闪烁等效果。
注意事项
- animateInterpolationSequence 函数依赖于 performance.now() 和 requestAnimationFrame API,请确保浏览器支持这些 API。
- 动画序列中的每个动画片段的持续时间单位是毫秒。
- 缓动函数应该接受一个 0 到 1 之间的值作为参数,并返回一个 0 到 1 之间的值,用于控制动画的速度变化。
- 在停止动画时,应该调用 animateInterpolationSequence 函数返回的函数,以取消 requestAnimationFrame 的回调。
总结
animateInterpolationSequence 函数提供了一种灵活的方式来控制动画序列的播放,可以用于实现各种复杂的动画效果。通过定义动画片段的起始值、持续时间、缓动函数等,可以精确地控制动画的播放过程。
终于介绍完啦!小伙伴们,这篇关于《requestAnimationFrame动画实现教程》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布文章相关知识,快来关注吧!
-
501 收藏
-
501 收藏
-
501 收藏
-
501 收藏
-
501 收藏
-
236 收藏
-
429 收藏
-
249 收藏
-
426 收藏
-
217 收藏
-
145 收藏
-
198 收藏
-
126 收藏
-
193 收藏
-
184 收藏
-
216 收藏
-
273 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 542次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 511次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 498次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 484次学习