SVG绘图入门:手把手教你绘制基础图形与动画特效

2026-11-30 0 阅读

SVG,即可缩放矢量图形(Scalable Vector Graphics),是一种基于可扩展标记语言(XML)的图形图像格式。它允许你创建一个可缩放且不失真的矢量图形。在网页设计和动画制作中,SVG因其灵活性和易用性而备受青睐。本篇文章将带你入门SVG绘图,从基础图形的绘制到动画特效的实现,一步步教你掌握SVG的魅力。

第一节:SVG基础概念

1.1 SVG文档结构

一个SVG文档的基本结构如下:

<svg
  xmlns="http://www.w3.org/2000/svg"
  width="200"
  height="200"
  version="1.1">
  <!-- 图形内容 -->
</svg>
  • xmlns: 定义SVG命名空间。
  • width 和 height: 设置SVG画布的宽度和高度。
  • version: 定义SVG的版本。

1.2 基础图形元素

SVG提供了多种图形元素,如矩形(rect)、圆形(circle)、椭圆(ellipse)、线(line)、折线(polyline)、多边形(polygon)和路径(path)等。以下是一些常见元素的示例:

<!-- 矩形 -->
<rect x="10" y="10" width="50" height="50" style="fill:blue;"/>

<!-- 圆形 -->
<circle cx="50" cy="50" r="30" style="fill:red;"/>

<!-- 线 -->
<line x1="50" y1="50" x2="100" y2="100" style="stroke:blue; stroke-width:2;"/>

<!-- 路径 -->
<path d="M10 10 L50 10 L50 50 L10 50 Z" style="fill:green;"/>

第二节:图形属性

SVG图形元素可以设置多种属性,如填充颜色(fill)、描边颜色(stroke)、描边宽度(stroke-width)等。以下是一些常用属性的示例:

<rect x="10" y="10" width="50" height="50"
     style="fill:blue; stroke:red; stroke-width:2;"/>

第三节:动画特效

SVG支持丰富的动画特效,包括渐变、遮罩、变换等。以下是一些常见的动画效果:

3.1 渐变

渐变可以通过<linearGradient>和<radialGradient>元素实现。以下是一个线性渐变的示例:

<svg>
  <defs>
    <linearGradient id="gradient" x1="0%" y1="0%" x2="100%" y2="0%">
      <stop offset="0%" style="stop-color:blue;"/>
      <stop offset="100%" style="stop-color:red;"/>
    </linearGradient>
  </defs>
  <rect x="10" y="10" width="100" height="100" style="fill:url(#gradient);"/>
</svg>

3.2 遮罩

遮罩可以通过<mask>元素实现。以下是一个使用遮罩的示例:

<svg>
  <defs>
    <mask id="mask" x="0" y="0" width="100" height="100">
      <rect x="0" y="0" width="100" height="100" fill="white"/>
    </mask>
  </defs>
  <rect x="10" y="10" width="100" height="100" style="fill:blue;"/>
  <rect x="10" y="10" width="100" height="100" mask="url(#mask)" fill="red"/>
</svg>

3.3 变换

SVG支持多种变换,如平移(translate)、旋转(rotate)、缩放(scale)和倾斜(skew)。以下是一个旋转动画的示例:

<svg>
  <circle cx="50" cy="50" r="30" style="fill:red;"/>
  <animateTransform
    attributeName="transform"
    type="rotate"
    from="0 50 50"
    to="360 50 50"
    dur="2s"
    repeatCount="indefinite"/>
</svg>

第四节:总结

通过本篇文章的学习,相信你已经对SVG绘图有了一定的了解。SVG绘图具有丰富的功能和强大的表现力,可以帮助你制作出精美的网页动画。在实际应用中,你可以根据自己的需求不断探索和尝试,发挥SVG的无限可能。

分享到: