SVG 的坐标系统和变换是理解 SVG 图形定位和操作的关键概念:
1. 坐标系统 SVG 使用笛卡尔坐标系,原点 (0,0) 位于左上角:
- x 轴向右为正方向
- y 轴向下为正方向
- 单位可以是 px、em、rem、cm、mm 等
2. viewBox 属性
viewBox 是 SVG 中最重要的属性之一,定义了 SVG 内容的坐标系和可视区域。
svg<svg viewBox="0 0 100 100" width="200" height="200"> <circle cx="50" cy="50" r="40" fill="red" /> </svg>
viewBox 参数:
min-x, min-y:左上角坐标width, height:可视区域的宽度和高度
viewBox 的作用:
- 定义内部坐标系
- 实现响应式缩放
- 控制显示比例
3. preserveAspectRatio 属性 控制 viewBox 如何在 SVG 视口中缩放和对齐。
svg<svg viewBox="0 0 100 100" preserveAspectRatio="xMidYMid meet" width="200" height="200"> <circle cx="50" cy="50" r="40" fill="blue" /> </svg>
参数说明:
align:对齐方式(xMin, xMid, xMax + YMin, YMid, YMax)meetOrSlice:缩放方式(meet:完整显示,slice:填充整个区域)
常用值:
xMidYMid meet:居中显示,保持比例(默认)xMidYMid slice:居中显示,填充整个区域none:不保持比例,拉伸填充
4. transform 属性
SVG 元素可以通过 transform 属性进行变换。
变换类型:
平移(translate)
svg<rect x="0" y="0" width="50" height="50" fill="red" transform="translate(100, 100)" />
旋转(rotate)
svg<rect x="0" y="0" width="50" height="50" fill="blue" transform="rotate(45, 25, 25)" />
参数:角度,旋转中心 x,旋转中心 y
缩放(scale)
svg<rect x="0" y="0" width="50" height="50" fill="green" transform="scale(2)" /> <rect x="0" y="0" width="50" height="50" fill="yellow" transform="scale(1.5, 0.5)" />
倾斜(skew)
svg<rect x="0" y="0" width="50" height="50" fill="purple" transform="skewX(30)" /> <rect x="0" y="0" width="50" height="50" fill="orange" transform="skewY(20)" />
组合变换
svg<rect x="0" y="0" width="50" height="50" fill="red" transform="translate(100, 100) rotate(45) scale(1.5)" />
5. 坐标系统嵌套
使用 <g> 元素创建局部坐标系统。
svg<svg viewBox="0 0 200 200"> <g transform="translate(50, 50)"> <circle cx="0" cy="0" r="20" fill="red" /> <circle cx="50" cy="0" r="20" fill="blue" /> <circle cx="25" cy="50" r="20" fill="green" /> </g> </svg>
6. 实际应用示例
响应式图标:
svg<svg viewBox="0 0 24 24" width="100%" height="100%"> <path d="M12 2L2 22h20L12 2zm0 4l7 14H5l7-14z" fill="currentColor" /> </svg>
居中对齐:
svg<svg viewBox="0 0 100 100" preserveAspectRatio="xMidYMid meet" width="300" height="200"> <rect x="0" y="0" width="100" height="100" fill="blue" /> </svg>
最佳实践:
- 始终使用 viewBox 实现响应式设计
- 使用 preserveAspectRatio 控制缩放行为
- 合理使用
<g>分组和变换简化代码 - 注意变换顺序会影响最终结果