What?SVG 还能做动画,这么强大还不学!(附源码和Demo)

929 阅读3分钟

大家好,我是 前端架构师 - 大卫

更多优质内容请关注微信公众号 @程序员大卫

初心为助前端人🚀,进阶路上共星辰✨,

您的点赞👍与关注❤️,是我笔耕不辍的灯💡。

图片

在线地址预览: codesandbox.io/p/sandbox/g…

当我第一次看到这动画效果时,还以为是通过 GIF、CSS3 或者 Canvas 制作的。结果出乎意料,居然是用 SVG 实现的!

也许你对 SVG 动画还不太熟悉,那就让我们一起开启这场奇妙的旅程吧!

什么是 SVG 动画?

SVG(Scalable Vector Graphics)是一种用于描述二维矢量图形的 XML 格式。除了静态图形,SVG 还支持动画效果,这为前端开发提供了更加灵活和强大的工具。

简单的 SVG 示例

我们从一个简单的例子开始:

<style>
  svg {
    border1px solid red;
  }
  svg line {
    stroke: #000/* 线条的颜色 */
  }
</style>
<svg width="200" height="200">
  <line x1="0" x2="100%" y1="50%" y2="50%"></line>
</svg>

图片

代码解析

<svg> 标签

  • 作用:定义 SVG 容器。
  • 属性
    • width 和 height:设置容器宽高(单位:像素),这里为 200px

<line> 标签

  • 作用:绘制直线。
  • 关键属性
    • x1 和 x2:起点和终点的水平坐标。
    • y1 和 y2:起点和终点的垂直坐标。

为直线添加动画

首先为直线增加一些样式:

svg line {
  stroke: #000;
+ stroke-width5;
+ stroke-dasharray: 10;
+ stroke-dashoffset: 0;
}

新增属性解析

  • stroke-width:设置线条的宽度(例如 5px)。
  • stroke-dasharray:定义虚线模式,例如 10 表示线段和空隙均为 10px
  • stroke-dashoffset:控制虚线起始偏移量。

图片

然后利用 stroke-dashoffset,为这条虚线添加动画效果:

svg line {
  stroke: black;
  stroke-width5;
  stroke-dasharray: 10;
  stroke-dashoffset: 0;
+ animation: dash 2s linear infinite;
}

+@keyframes dash {
to {
    stroke-dashoffset: -100/* 虚线反方向移动 */
  }
}

属性说明

  • 动画通过改变 stroke-dashoffset,让虚线看起来在移动。
  • 2s linear infinite 表示动画每 2 秒 循环一次,且速度匀速。

图片

绘制折线动画

使用 <path> 标签,我们可以绘制更复杂的路径:

<style>
  svg {
    border1px solid red;
  }
</style>
<svg width="200" height="200">
  <path d="M125.69 0.44 L182.46 16.41 L0.23 113" />
</svg>

图片

看上去怎么有点怪,因为 path 填充了黑色的背景颜色。这时只需加入 CSS 样式 fill: none:

svg path {
  fill: none;
  stroke: blue;
}

图片

再加上之前例子的动画 CSS

svg path {
    fill: none;
    stroke: blue;
  + stroke-width5;
  + stroke-dasharray: 10;
  + stroke-dashoffset: 0;
  + animation: dash 2s linear infinite;
}

+ @keyframes dash {
to {
    stroke-dashoffset: -100;
  }
}

图片

🎉🎉🎉 是不是已经实现了开头的线条动画效果?

创建箭头移动动画

不仅是线条,普通元素也能沿着路径移动!利用 offset-path 属性,我们可以实现箭头沿路径运动的效果:

<style>
  .box {
    width200px;
    height200px;
    border1px solid red;
    position: relative;
  }
.arrow {
    backgroundurl(./images/arrow.png) no-repeat 00 / contain;
    width45px;
    height30px;
    offset-path: path("M125.69 0.44 L182.46 16.41 L0.23 113");
    animation: arrow-go 4s linear infinite;
  }
@keyframes arrow-go {
    0% {
      offset-distance: 0%;
    }
    100% {
      offset-distance: 100%;
    }
  }
</style>
<div class="box">
  <div class="arrow"></div>
</div>

图片

效果解析

  • offset-path:设置运动路径,其值可以是路径字符串(与 <path> 元素的 d 属性语法相似)
  • offset-distance:控制元素在路径上的移动距离,配合动画可以实现平滑移动。

通过调整 opacity 属性,你还可以进一步增强动画效果,例如实现淡入淡出或者旋转。

绘制自定义路径

您可以通过访问 https://yqnn.github.io/svg-path-editor/ 轻松绘制各种自定义路径。

图片

总结

通过以上示例,我们探索了 SVG 的基本用法和动画实现方式。无论是简单的直线动画、折线动画,还是路径运动,SVG 都能轻松胜任。

示例源码地址

github.com/zm8/wechat-…

最后

点赞👍 + 关注➕ + 收藏❤️ = 学会了🎉。

更多优质内容关注公众号,@前端大卫