从零开始,轻松掌握SVG绘图教程:基础入门必看攻略

2026-11-01 0 阅读

SVG简介

SVG(可缩放矢量图形)是一种基于可扩展标记语言(XML)的图形图像格式。它允许你创建矢量图形,这些图形可以任意缩放而不失真。SVG在网页设计、动画制作和移动应用开发等领域都有广泛的应用。

SVG基础元素

1. <svg> 标签

SVG绘图的开始和结束都包裹在 <svg> 标签中。这个标签包含了图形的尺寸和视图。

<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg">
  <!-- 图形内容 -->
</svg>

2. <circle> 标签

<circle> 标签用于绘制圆形。它需要 cx(中心点的x坐标)、cy(中心点的y坐标)和 r(半径)三个属性。

<circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />

3. <rect> 标签

<rect> 标签用于绘制矩形。它需要 x(矩形的x坐标)、y(矩形的y坐标)、width(矩形的宽度)和 height(矩形的高度)四个属性。

<rect x="10" y="10" width="100" height="50" stroke="black" stroke-width="3" fill="blue" />

4. <line> 标签

<line> 标签用于绘制直线。它需要 x1、y1(起始点的坐标)、x2、y2(结束点的坐标)四个属性。

<line x1="10" y1="10" x2="200" y2="200" stroke="black" stroke-width="3" />

5. <polyline> 标签

<polyline> 标签用于绘制多边形。它需要一系列的坐标点,使用 points 属性来指定。

<polyline points="10,10 40,40 90,40 10,10" stroke="black" stroke-width="3" fill="none" />

6. <polygon> 标签

<polygon> 标签与 <polyline> 类似,但它会自动填充多边形。

<polygon points="50,10 10,40 50,80 90,40" stroke="black" stroke-width="3" fill="yellow" />

SVG颜色与样式

SVG支持丰富的颜色和样式设置。

1. 颜色

  • 颜色可以通过 fill 和 stroke 属性来设置。
  • 可以使用颜色名、十六进制颜色值和RGB颜色值。
<circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />

2. 样式

  • 可以使用 style 属性来设置元素的样式。
  • 支持所有CSS样式属性。
<circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" style="opacity: 0.5;" />

SVG动画

SVG支持丰富的动画效果。

1. <animate> 标签

<animate> 标签用于定义动画。

<circle cx="50" cy="50" r="40" fill="red">
  <animate attributeName="cx" from="50" to="150" dur="2s" repeatCount="indefinite" />
</circle>

2. <animateTransform> 标签

<animateTransform> 标签用于定义变换动画。

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

总结

通过以上内容,你已经对SVG绘图有了基本的了解。SVG绘图是一个简单而又强大的工具,可以帮助你创建出精美的图形和动画。希望这篇教程能够帮助你轻松入门SVG绘图。

分享到: