IMLC
Home/html/wave-text
Article

动画效果 - 文字波浪效果

L
Lawrence
|Reading time

动画效果 - 文字波浪效果

本教程假设你已经基本了解了 CSS 和其动画接口 keyframes

**实现思路**

创建一个渐变动画的背景图案 然后使用 `background-clip: text` 使文字剪裁背景

第一步: 创建渐变背景

css
.wave {
    background: linear-gradient(
    90deg,
    #000 0%,
    #151515 40%,
    #FFF 50%,
    #151515 60%,
    #000 100%
    );
}

第二步: 创建背景动画

使用 `background-size` 和 `background-position` 来完成从左向右移动的动画.

关于为什么 200%~0% 是从左往右移动, 请阅读 MDN的 [background-position 百分比值的含义](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/background-position#regarding_percentages). 或者让 AI 给你解释.

css
.wave {
    background: linear-gradient(
        90deg,
        #000 0%,
        #151515 40%,
        #FFF 50%,
        #151515 60%,
        #000 100%
    ); 
    background-size: 200% auto;
    animation: wave 3s linear infinite;
}


@keyframes wave {
    0% {
        background-position: 200% center;
    }
    100% {
        background-position: 0% center;
    }
}

第三步: 剪裁文字

使用 `background-clip: text` 使文字剪裁背景 使用 `color: transparent` 使文字透明, 否则文字颜色遮住背景

css
.wave {
    background: linear-gradient(
        90deg,
        #000 0%,
      #282828 25%,
        #FFF 50%,
      #282828 75%,
        #000 100%
    );
    background-size: 200% auto;
    background-clip: text;
    color: transparent;
    animation: wave 3s linear infinite;
}


@keyframes wave {
    0% {
        background-position: 200% center;
    }
    100% {
        background-position: 0% center;
    }
}


浏览器兼容性和无障碍访问

添加 `-webkit-background-clip` 和 `-webkit-text-fill-color` 保证浏览器兼容性.

添加 `@media (prefers-reduced-motion: reduce)` 以遵守操作系统的“减弱动态效果”或“减少动画”设置.

css

.wave {
    background: linear-gradient(
        90deg,
        #000 0%,
      #282828 25%,
        #FFF 50%,
      #282828 75%,
        #000 100%
    );
    background-size: 200% auto;
    background-clip: text;
    -webkit-background-clip: text;
    color: transparent;
    -webkit-text-fill-color: transparent;
    animation: wave 3s linear infinite;
}

@media (prefers-reduced-motion: reduce) {
    .wave {
        animation: none;
        color: #000000
    }
}