You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CSS关键帧动画编辑器:特定时间点样式插值实现方案咨询

CSS关键帧动画编辑器的核心难题与尝试方案

我正在开发一款基于CSS关键帧的动画编辑器,需要实现时间轴播放预览和关键帧编辑功能。目前遇到的核心问题是:在动画预览时,要在两个关键帧之间的特定时间点对HTML元素样式进行插值计算——像top这类简单数值属性可以用JS直接计算,但border-radius这类格式复杂的属性(比如从"50% 20% 10% 10%"插值到"20% / 10%"),用JS实现插值的难度极大。

我尝试过用CSS原生方式只播放特定关键帧范围,但animation-range、animation-range-start、animation-range-end这类属性仍处于实验阶段,无法适配当前的生产环境场景。

以下是我目前尝试的CSS+JS代码:

<head>
    <style>
        @keyframes colorAnim {
            0% {
                color: black;
            }

            50% {
                color: red;
            }

            100% {
                color: green;
            }
        }

        .animated-element-with-offset {
            animation: colorAnim 100ms infinite;
            animation-play-state: paused;
        }
    </style>
</head>

<body>
    <div class="animated-element-with-offset" id="some-element-you-want-to-animate">
        Text Color Animation frame #50: Color expected is red
    </div>

    <button onclick="interpretAndPauseAnimation(50)">Interpret and Pause Animation at 50%</button>

    <script>
        const element = document.getElementById("some-element-you-want-to-animate");
        let start, previousTimeStamp;

        let duration = 100;
        let endDuration = 49;

        let done = false;

        function step(timeStamp) {
            if (start === undefined) {
                start = timeStamp;
            }
            const elapsed = timeStamp - start;

            if (previousTimeStamp !== timeStamp) {
                if (elapsed > duration * (endDuration / 100)) {
                    done = true;
                    element.style.animationPlayState = 'paused';
                } else {
                    element.style.animationPlayState = 'running';
                }
            }

            if (elapsed < duration) {
                previousTimeStamp = timeStamp;
                if (!done) {
                    window.requestAnimationFrame(step);
                }
            }
        }

        function interpretAndPauseAnimation(keyframePercentage) {
            start = undefined;
            previousTimeStamp = undefined;
            done = false;
            window.requestAnimationFrame(step);
        }

        window.requestAnimationFrame(step);

    </script>
</body>

</html>

内容的提问来源于stack exchange,提问作者sachaamm

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 02:05:08