使用 requestAnimationFrame 实现动画序列

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

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

序列猴子开放平台 序列猴子开放平台

具有长序列、多模态、单模型、大数据等特点的超大规模语言模型

序列猴子开放平台 0 查看详情 序列猴子开放平台 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  {        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 实现动画序列的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/237123.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年11月3日 23:47:53
下一篇 2025年11月3日 23:48:28

相关推荐

发表回复

登录后才能评论
关注微信