自己的笔记之“动画背景图需要控制动画滚动速度且丝滑过渡,暂停后再开始时是在暂停的位置上继续开始动画”

3 阅读1分钟

开始记录

html:
        <div>
            <div class="he-bg ant-he"></div>
        </div>
css:
        .he-bg {
            position: absolute;
            top: 0;
            left: 0;
            width: 30rem;
            height: 100%;
            background-image: url(""); 
            /* 替换为你的背景图路径,且如你的igm宽度是15rem,所以你的盒子宽度需要是img图片宽度的两倍 */
            background-size: contain;
            background-repeat: repeat-x;
            transition: transform 0.5s ease; /* 添加过渡效果 */
        }
        .ant-he {
            animation: moveBackground 5s linear infinite; /* 无限循环滚动 */
        }
        
        @keyframes moveBackground {
            0% {
                transform: translateX(0);
            }
            100% {
                transform: translateX(-15rem);
            }
        }
        
    js:
function setAnimationSpeed(speed, shouldPause = false) {

    const element = document.querySelector(".ant-he");
    if (!element) {
        console.error("元素未找到,请检查选择器是否正确");
        return;
    }
    // 获取当前动画的计算样式
    const computedStyle = getComputedStyle(element);
    const animationDuration = parseFloat(computedStyle.animationDuration);//动画持续时间,单位秒
    const animationName = computedStyle.animationName;//动画名称
    const animationIterationCount = computedStyle.animationIterationCount;//动画播放次数
    const animationTimingFunction = computedStyle.animationTimingFunction;//动画时间函数,常见值:-   
    `linear`:匀速
-   `ease`:慢 → 快 → 慢(默认)
-   `ease-in`:开始慢
-   `ease-out`:结束慢
-   `ease-in-out`:开始和结束都慢
-   `cubic-bezier(x1, y1, x2, y2)`:自定义缓动曲线

    const animationDelay = computedStyle.animationDelay;//动画延迟时间
    const animationFillMode = computedStyle.animationFillMode;//动画填充模式

    // 获取当前动画已经播放的时间,是毫秒单位。1秒=1000毫秒
    const currentTime = element.getAnimations()[0]?.currentTime || 0;
    const progress = currentTime / (animationDuration * 1000);//时间单位不一样所以需要*1000

    // 计算新的动画持续时间
    const newDuration = speed;
    const newCurrentTime = progress * newDuration * 1000;

    // 动态调整动画
    element.style.animation = `${animationName} ${newDuration}s ${animationTimingFunction} ${animationDelay} ${animationIterationCount} ${animationFillMode}`;

    // 设置动画的当前时间,保持播放进度
    const animation = element.getAnimations()[0];

    if (animation) {
        animation.currentTime = newCurrentTime ? newCurrentTime : 0;
        // 如果 shouldPause 为 true,则暂停动画
        if (shouldPause) {
            animation.pause();
        } else {
            animation.play();
        }
    } else {
        // 如果动画不存在,直接设置 playState
        if (shouldPause) {
            element.style.animationPlayState = "paused";
        } else {
            element.style.animationPlayState = "running";
        }
    }
}