svg文字动画

svg文字动画

演示效果

准备 SVG 文字

动态文字动画需要一个包含文字路径的 SVG,使用 <path> 元素定义文字形状。以下是一个典型的 SVG 结构:

HTML
1
2
3
<svg class="animated-text" preserveAspectRatio="xMidYMid meet" style="width: 100%; height: 100%;" viewBox="0 0 300 100" xmlns="http://www.w3.org/2000/svg">
  <path d="M10 80 Q 95 10 180 80" fill="currentColor" style="--path-length: 200;"/>
</svg>

SVG <path> 属性定义

以下是 <path> 元素中与动画相关的关键属性的说明:

  • fill 属性:控制路径填充颜色。

    • 作用:决定路径内部颜色,动画中常用于填充效果。
    • 推荐值fill="currentColor" 使填充与父元素颜色一致;fill="transparent" 用于描边阶段。
    • 生成方式:Rust 代码中通过 Path::new().set("fill", "currentColor") 设置。
    • 注意:动画初期通常设为 transparent,后期切换到 currentColor
  • style 属性:设置 CSS 自定义属性。

    • 作用:定义 --path-length,表示路径长度,用于 CSS 动画。
    • 生成方式:Rust 代码通过 PathBuilder 计算路径长度(calculate_distancecalculate_curve_length),设置如 style="--path-length: 200;"
    • 示例style="--path-length: 200;" 表示路径长 200 单位。
    • 注意:长度需精确,可用 JavaScript 的 path.getTotalLength() 验证。

SVG 配置

  • 类名:为 <svg> 设置 class="animated-text"
  • 视图框:使用 viewBox="0 0 300 100" 适配内容。
  • 比例preserveAspectRatio="xMidYMid meet" 确保居中缩放。

编写 CSS 动画

CSS 动画通过 stroke-dasharraystroke-dashoffset 实现描边效果,结合 fill 切换填充。以下是完整代码:

CSS
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
.animated-text path {
  fill: transparent;
  stroke: currentColor;
  stroke-width: 2;
  stroke-dasharray: var(--path-length);
  stroke-dashoffset: var(--path-length);
  animation: logo-anim 10s ease-in-out infinite;
}

@keyframes logo-anim {
  0% {
    stroke-dashoffset: var(--path-length);
    fill: transparent;
    opacity: 0;
  }
  10% {
    opacity: 1;
    stroke-dashoffset: var(--path-length);
  }
  50% {
    stroke-dashoffset: 0;
    fill: transparent;
  }
  60% {
    stroke-dashoffset: 0;
    fill: currentColor;
  }
  80% {
    stroke-dashoffset: 0;
    fill: currentColor;
  }
  90% {
    stroke-dashoffset: var(--path-length);
    fill: transparent;
  }
  100% {
    stroke-dashoffset: var(--path-length);
    fill: transparent;
    opacity: 0;
  }
}

@media (prefers-color-scheme: dark) {
  .animated-text path {
    stroke: currentColor;
  }
}
  • 说明
    • 样式fill: transparent 初始无填充,stroke: currentColor 描边与父元素颜色一致,stroke-width: 2 设置描边粗细。
    • 动画stroke-dasharraystroke-dashoffset 使用 --path-length 控制虚线和偏移。
    • 流程:0%-10% 淡入,50% 描边完成,60%-80% 填充颜色,90%-100% 描边退回并淡出。
    • 参数10s 持续时间,ease-in-out 缓动,infinite 循环。
    • 暗色模式:确保描边颜色适配主题。