从零开始:SVG绘图教程,手把手教你绘制精美图形

2026-09-13 0 阅读

SVG,即可缩放矢量图形(Scalable Vector Graphics),是一种基于可扩展标记语言(XML)的图形图像格式。SVG格式的图形可以无限放大或缩小而不失真,非常适合用于网页设计、动画制作等领域。本教程将从零开始,手把手教你如何使用SVG绘制精美图形。

第一节:SVG基础

1.1 SVG元素

SVG图形由多个元素组成,主要包括:

  • <svg>:SVG图形的根元素,定义了图形的宽度和高度。
  • <circle>:圆形元素。
  • <rect>:矩形元素。
  • <line>:直线元素。
  • <polyline>:折线元素。
  • <polygon>:多边形元素。
  • <ellipse>:椭圆元素。

1.2 属性

每个SVG元素都有许多属性,用于描述图形的样式和位置。以下是一些常用的属性:

  • xy:元素的坐标。
  • widthheight:元素的宽度和高度。
  • r:圆形的半径。
  • cxcy:圆形的圆心坐标。
  • rxry:椭圆的半长轴和半短轴。
  • stroke:边框颜色。
  • stroke-width:边框宽度。
  • fill:填充颜色。

第二节:绘制基本图形

2.1 绘制圆形

以下代码演示了如何使用SVG绘制一个圆形:

<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg">
  <circle cx="100" cy="100" r="50" stroke="black" stroke-width="2" fill="red" />
</svg>

2.2 绘制矩形

以下代码演示了如何使用SVG绘制一个矩形:

<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg">
  <rect x="50" y="50" width="100" height="100" stroke="black" stroke-width="2" fill="blue" />
</svg>

2.3 绘制直线

以下代码演示了如何使用SVG绘制一条直线:

<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg">
  <line x1="50" y1="50" x2="150" y2="150" stroke="black" stroke-width="2" />
</svg>

第三节:组合图形

在实际应用中,我们经常需要将多个图形组合在一起,形成复杂的图形。以下代码演示了如何将圆形和矩形组合在一起:

<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg">
  <circle cx="100" cy="100" r="50" stroke="black" stroke-width="2" fill="red" />
  <rect x="50" y="50" width="100" height="100" stroke="black" stroke-width="2" fill="blue" />
</svg>

第四节:动画效果

SVG支持动画效果,可以用于制作动态图形。以下代码演示了如何使用SVG制作一个圆形的旋转动画:

<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg">
  <circle cx="100" cy="100" r="50" stroke="black" stroke-width="2" fill="red">
    <animateTransform attributeName="transform" type="rotate" from="0 100 100" to="360 100 100" dur="2s" repeatCount="indefinite" />
  </circle>
</svg>

第五节:进阶技巧

5.1 使用SVG滤镜

SVG滤镜可以用于实现各种图形效果,如模糊、光照等。以下代码演示了如何使用SVG滤镜实现模糊效果:

<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg">
  <filter id="blur" x="0" y="0" width="200" height="200">
    <feGaussianBlur in="SourceGraphic" stdDeviation="5" />
  </filter>
  <circle cx="100" cy="100" r="50" stroke="black" stroke-width="2" fill="red" filter="url(#blur)" />
</svg>

5.2 使用SVG样式表

SVG支持CSS样式表,可以用于设置图形的样式。以下代码演示了如何使用CSS样式表设置图形的边框颜色和填充颜色:

<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg">
  <style>
    .red {
      fill: red;
      stroke: black;
      stroke-width: 2;
    }
  </style>
  <circle class="red" cx="100" cy="100" r="50" />
</svg>

总结

通过本教程,你已掌握了SVG绘图的基本技能。在实际应用中,你可以根据自己的需求,不断学习和探索SVG的更多功能。相信在不久的将来,你将能够创作出精美的SVG图形。

分享到: