首页 > web前端 > js教程 > 正文

使用 requestAnimationFrame 实现动画序列

碧海醫心
发布: 2025-08-04 14:48:25
原创
625人浏览过

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

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

bee餐饮点餐外卖小程序
bee餐饮点餐外卖小程序

bee餐饮点餐外卖小程序是针对餐饮行业推出的一套完整的餐饮解决方案,实现了用户在线点餐下单、外卖、叫号排队、支付、配送等功能,完美的使餐饮行业更高效便捷!功能演示:1、桌号管理登录后台,左侧菜单 “桌号管理”,添加并管理你的桌号信息,添加以后在列表你将可以看到 ID 和 密钥,这两个数据用来生成桌子的二维码2、生成桌子二维码例如上面的ID为 308,密钥为 d3PiIY,那么现在去左侧菜单微信设置

bee餐饮点餐外卖小程序 1
查看详情 bee餐饮点餐外卖小程序
  • 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)
);
登录后复制
<canvas id="canvas" width="400" height="180"></canvas>
登录后复制

在这个示例中,renderStar 函数用于绘制星形。animateInterpolationSequence 函数被用来控制星形的透明度变化,实现淡入淡出、闪烁等效果。

注意事项

  • animateInterpolationSequence 函数依赖于 performance.now() 和 requestAnimationFrame API,请确保浏览器支持这些 API。
  • 动画序列中的每个动画片段的持续时间单位是毫秒。
  • 缓动函数应该接受一个 0 到 1 之间的值作为参数,并返回一个 0 到 1 之间的值,用于控制动画的速度变化。
  • 在停止动画时,应该调用 animateInterpolationSequence 函数返回的函数,以取消 requestAnimationFrame 的回调。

总结

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

以上就是使用 requestAnimationFrame 实现动画序列的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

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