📐 SVG基础完全指南
🌟 SVG简介
SVG (Scalable Vector Graphics) 是一种基于 XML 的矢量图形格式。与位图(如PNG、JPG)不同,SVG 图形可以无限缩放而不失真,非常适合响应式设计和高清显示。
🎯 SVG自适应原理
1. 核心概念
- 📏 viewport: SVG的可见区域
- 🖼️ viewBox: 坐标系统定义
- 🔄 preserveAspectRatio: 宽高比例控制
2. 详细解析
html
<svg width="500" height="200"
viewBox="0 0 500 200"
preserveAspectRatio="xMidYMid meet">
<!-- SVG内容 -->
</svg>preserveAspectRatio参数说明
第一个参数(对齐方式):
xMin: 左对齐xMid: 水平居中xMax: 右对齐YMin: 顶部对齐YMid: 垂直居中YMax: 底部对齐
第二个参数(缩放方式):
meet: 保持比例,完整显示slice: 保持比例,裁剪显示none: 拉伸适应,可能变形
🎭 SVG动画
1. Transform变换
html
<svg width='500' height='200' viewBox='0 0 500 200'>
<!--
transform属性可以组合多个变换:
1. translate(10,20) - 平移
2. rotate(30) - 旋转
3. matrix(2 1 -1 2 50 0) - 矩阵变换
-->
<rect x='0' y='0'
width='100' height='50'
fill='red'
transform='translate(10,20) rotate(30) matrix(2 1 -1 2 50 0)' />
</svg>🔄 矩阵变换原理
js
/**
* matrix(2 1 -1 2 50 0) 矩阵计算:
* [2,-1,50] --> 2*x + (-1)*y + 50 = new_x
* [1,2,0] --> 1*x + 2*y + 0 = new_y
*
* 顶点坐标变换示例:
* [0,0] --> [50,0]
* [100,0] --> [250,100]
*/2. 🎬 SVG描边动画
css
/* 路径动画效果 */
.svgPath path {
fill: transparent;
stroke: #fff;
/* 组合两个动画效果 */
animation:
stroke 15s linear 1 forwards, /* 描边动画 */
fill 2s linear 2s 1 forwards; /* 填充动画 */
}
/* 描边动画关键帧 */
@keyframes stroke {
0% {
stroke-dasharray: 2257; /* 虚线总长度 */
stroke-dashoffset: 2257; /* 虚线偏移量 */
}
100% {
stroke-dasharray: 2257;
stroke-dashoffset: 0; /* 偏移量变为0,显示完整线条 */
}
}
/* 填充动画关键帧 */
@keyframes fill {
from { fill: transparent; }
to { fill: white; }
}📝 SVG基础图形
1. 通用属性
| 属性 | 说明 | 示例 |
|---|---|---|
fill | 填充颜色 | fill="red" |
stroke | 边框颜色 | stroke="blue" |
stroke-width | 边框宽度 | stroke-width="2" |
opacity | 整体透明度 | opacity="0.5" |
2. 🔲 基础图形元素
矩形 (rect)
html
<rect x="10" y="10"
width="100" height="50"
rx="5" ry="5" /> <!-- 圆角属性 -->圆形 (circle)
html
<circle cx="100" cy="100" r="50" />
<!-- cx,cy为圆心坐标,r为半径 -->椭圆 (ellipse)
html
<ellipse cx="100" cy="100"
rx="100" ry="50" />
<!-- rx,ry分别为水平、垂直半径 -->3. ✏️ 路径绘制
html
<path d="M150 0 L75 200 L225 200 Z" />
<!--
路径命令说明:
- M: 移动到点(MoveTo)
- L: 画线到点(LineTo)
- Z: 闭合路径
大写表示绝对坐标,小写表示相对坐标
-->🎨 高级特性
1. 滤镜效果
html
<svg>
<defs>
<filter id="blur">
<!-- 高斯模糊 -->
<feGaussianBlur stdDeviation="5"/>
</filter>
</defs>
<rect filter="url(#blur)" />
</svg>2. 渐变效果
html
<svg>
<defs>
<!-- 线性渐变 -->
<linearGradient id="grad1">
<stop offset="0%" stop-color="red"/>
<stop offset="100%" stop-color="blue"/>
</linearGradient>
</defs>
<rect fill="url(#grad1)" />
</svg>💡 最佳实践
- 使用
viewBox实现响应式设计 - 合理使用
g元素组织复杂图形 - 优化路径数据减少文件体积
- 使用CSS控制样式便于维护