SVG 入门教程
1. 什么是 SVG?
SVG(Scalable Vector Graphics,可缩放矢量图形)是一种基于 XML 的矢量图形格式。它可以在网页中使用,支持缩放、不失真、动画和交互。
2. 为什么使用 SVG?
- 清晰度:无论放大或缩小,SVG 仍然保持清晰。
- 文件体积小:相比于 PNG、JPG,SVG 在某些情况下更小。
- 可编程:可以通过 CSS 和 JavaScript 控制。
- 支持动画:可以使用 CSS 或 JavaScript 进行动画处理。
- 跨平台:可以用于网页、移动端、小程序等。
3. 基本语法
SVG 是基于 XML 的,基本结构如下:
<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="100" r="50" fill="blue" />
</svg>
解释:
<svg>
:定义 SVG 画布。width
/height
:定义宽高。xmlns
:XML 命名空间。<circle>
:绘制一个圆。cx
,cy
:圆心坐标。r
:半径。fill
:填充颜色。
4. 常见图形元素
4.1 矩形 <rect>
<rect x="10" y="10" width="100" height="50" fill="red" stroke="black" stroke-width="2" />
属性说明:
x
/y
:矩形左上角坐标。width
/height
:矩形宽高。fill
:填充颜色。stroke
/stroke-width
:边框颜色和宽度。
4.2 圆形 <circle>
<circle cx="50" cy="50" r="40" fill="yellow" stroke="black" stroke-width="2" />
4.3 椭圆 <ellipse>
<ellipse cx="100" cy="50" rx="80" ry="40" fill="green" />
cx
,cy
:中心点。rx
,ry
:横向半径、纵向半径。
4.4 直线 <line>
<line x1="10" y1="10" x2="100" y2="100" stroke="blue" stroke-width="2" />
4.5 多边形 <polygon>
<polygon points="50,15 90,80 10,80" fill="purple" />
points
:每个点的 x,y 坐标。
4.6 折线 <polyline>
<polyline points="10,10 50,50 90,10" stroke="black" fill="none" />
4.7 文字 <text>
<text x="50" y="50" font-size="20" fill="black">Hello SVG</text>
5. 高级用法
5.1 渐变填充
<defs>
<linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="0%">
<stop offset="0%" stop-color="red" />
<stop offset="100%" stop-color="blue" />
</linearGradient>
</defs>
<rect x="10" y="10" width="100" height="100" fill="url(#grad1)" />
5.2 SVG 动画
1. 通过 <animate>
<circle cx="50" cy="50" r="20" fill="blue">
<animate attributeName="cx" from="50" to="150" dur="2s" repeatCount="indefinite" />
</circle>
2. 通过 CSS
@keyframes move {
0% { transform: translateX(0); }
100% { transform: translateX(100px); }
}
circle { animation: move 2s infinite alternate; }
6. 交互性(使用 JavaScript 操作 SVG)
<svg id="mysvg" width="200" height="200">
<circle id="mycircle" cx="100" cy="100" r="50" fill="blue" />
</svg>
<script>
document.getElementById("mycircle").addEventListener("click", function() {
this.setAttribute("fill", "red");
});
</script>
点击圆形后颜色变红。
7. 结论
SVG 是强大的矢量图形技术,适用于图标、动画、数据可视化等场景。学习 SVG 可以让你在前端开发中更灵活地使用图形。