0

0

使用 requestAnimationFrame 实现动画序列

碧海醫心

碧海醫心

发布时间:2025-08-04 14:48:25

|

628人浏览过

|

来源于php中文网

原创

使用 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 是一个数组,包含一系列动画片段的描述。

每个动画片段是一个对象,包含以下属性:

极限网络办公Office Automation
极限网络办公Office Automation

专为中小型企业定制的网络办公软件,富有竞争力的十大特性: 1、独创 web服务器、数据库和应用程序全部自动傻瓜安装,建立企业信息中枢 只需3分钟。 2、客户机无需安装专用软件,使用浏览器即可实现全球办公。 3、集成Internet邮件管理组件,提供web方式的远程邮件服务。 4、集成语音会议组件,节省长途话费开支。 5、集成手机短信组件,重要信息可直接发送到员工手机。 6、集成网络硬

下载
  • 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 函数提供了一种灵活的方式来控制动画序列的播放,可以用于实现各种复杂的动画效果。通过定义动画片段的起始值、持续时间、缓动函数等,可以精确地控制动画的播放过程。

相关专题

更多
php源码安装教程大全
php源码安装教程大全

本专题整合了php源码安装教程,阅读专题下面的文章了解更多详细内容。

65

2025.12.31

php网站源码教程大全
php网站源码教程大全

本专题整合了php网站源码相关教程,阅读专题下面的文章了解更多详细内容。

43

2025.12.31

视频文件格式
视频文件格式

本专题整合了视频文件格式相关内容,阅读专题下面的文章了解更多详细内容。

35

2025.12.31

不受国内限制的浏览器大全
不受国内限制的浏览器大全

想找真正自由、无限制的上网体验?本合集精选2025年最开放、隐私强、访问无阻的浏览器App,涵盖Tor、Brave、Via、X浏览器、Mullvad等高自由度工具。支持自定义搜索引擎、广告拦截、隐身模式及全球网站无障碍访问,部分更具备防追踪、去谷歌化、双内核切换等高级功能。无论日常浏览、隐私保护还是突破地域限制,总有一款适合你!

41

2025.12.31

出现404解决方法大全
出现404解决方法大全

本专题整合了404错误解决方法大全,阅读专题下面的文章了解更多详细内容。

204

2025.12.31

html5怎么播放视频
html5怎么播放视频

想让网页流畅播放视频?本合集详解HTML5视频播放核心方法!涵盖<video>标签基础用法、多格式兼容(MP4/WebM/OGV)、自定义播放控件、响应式适配及常见浏览器兼容问题解决方案。无需插件,纯前端实现高清视频嵌入,助你快速打造现代化网页视频体验。

9

2025.12.31

关闭win10系统自动更新教程大全
关闭win10系统自动更新教程大全

本专题整合了关闭win10系统自动更新教程大全,阅读专题下面的文章了解更多详细内容。

8

2025.12.31

阻止电脑自动安装软件教程
阻止电脑自动安装软件教程

本专题整合了阻止电脑自动安装软件教程,阅读专题下面的文章了解更多详细教程。

3

2025.12.31

html5怎么使用
html5怎么使用

想快速上手HTML5开发?本合集为你整理最实用的HTML5使用指南!涵盖HTML5基础语法、主流框架(如Bootstrap、Vue、React)集成方法,以及无需安装、直接在线编辑运行的平台推荐(如CodePen、JSFiddle)。无论你是新手还是进阶开发者,都能轻松掌握HTML5网页制作、响应式布局与交互功能开发,零配置开启高效前端编程之旅!

2

2025.12.31

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
如何进行WebSocket调试
如何进行WebSocket调试

共1课时 | 0.1万人学习

TypeScript全面解读课程
TypeScript全面解读课程

共26课时 | 5万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号