全面介绍SVG变换技术,包括平移、旋转、缩放、倾斜和矩阵变换。掌握SVG图形变换的核心技术。 SVG变换允许对图形元素进行平移、旋转、缩放、倾斜等操作,是创建复杂图形和动画的基础。
| 变换类型 | 函数 | 说明 |
|---|---|---|
| 平移 | translate() | 移动元素位置 |
| 旋转 | rotate() | 绕点旋转元素 |
| 缩放 | scale() | 放大或缩小元素 |
| 倾斜 | skewX(), skewY() | 倾斜变形 |
| 矩阵 | matrix() | 通用变换矩阵 |
<element transform="变换函数"/>
translate()函数将元素从当前位置移动到新位置。
<rect x="20" y="20" width="60" height="40" fill="#3498db" opacity="0.3"/>
<rect x="20" y="20" width="60" height="40" fill="#3498db" transform="translate(100, 30)"/>
rotate()函数将元素绕指定点旋转。
<rect x="50" y="30" width="60" height="40" fill="#3498db" opacity="0.3"/>
<rect x="50" y="30" width="60" height="40" fill="#3498db" transform="rotate(30)"/>
<rect x="180" y="30" width="60" height="40" fill="#e74c3c" opacity="0.3"/>
<rect x="180" y="30" width="60" height="40" fill="#e74c3c" transform="rotate(45, 210, 50)"/>
scale()函数改变元素的大小。
<rect x="30" y="40" width="40" height="40" fill="#3498db" opacity="0.3"/>
<rect x="30" y="40" width="40" height="40" fill="#3498db" transform="scale(1.5)"/>
<rect x="180" y="40" width="40" height="40" fill="#e74c3c" opacity="0.3"/>
<rect x="180" y="40" width="40" height="40" fill="#e74c3c" transform="scale(0.5)"/>
skewX()和skewY()函数沿X轴或Y轴倾斜元素。
<rect x="30" y="40" width="50" height="50" fill="#3498db" transform="skewX(20)"/>
<rect x="130" y="40" width="50" height="50" fill="#e74c3c" transform="skewY(15)"/>
<rect x="220" y="40" width="50" height="50" fill="#2ecc71" transform="skewX(10) skewY(10)"/>
多个变换函数可以组合使用,按顺序依次执行。
<rect x="60" y="40" width="40" height="40" fill="#3498db" opacity="0.3"/>
<rect x="60" y="40" width="40" height="40" fill="#3498db" transform="translate(100, 20) rotate(30) scale(1.2)"/>
<circle cx="150" cy="100" r="80" fill="none" stroke="#333" stroke-width="3"/>
<circle cx="150" cy="100" r="5" fill="#333"/>
<line x1="150" y1="100" x2="150" y2="40" stroke="#333" stroke-width="4" stroke-linecap="round" transform="rotate(60, 150, 100)"/>
<line x1="150" y1="100" x2="150" y2="55" stroke="#3498db" stroke-width="3" stroke-linecap="round" transform="rotate(180, 150, 100)"/>
<line x1="150" y1="100" x2="150" y2="70" stroke="#e74c3c" stroke-width="2" stroke-linecap="round" transform="rotate(270, 150, 100)"/>
<rect x="70" y="55" width="40" height="40" fill="#3498db" transform="rotate(0, 90, 75)"/>
<rect x="70" y="55" width="40" height="40" fill="#e74c3c" transform="rotate(45, 90, 75)"/>
<rect x="70" y="55" width="40" height="40" fill="#2ecc71" transform="rotate(90, 90, 75)"/>
<rect x="70" y="55" width="40" height="40" fill="#f39c12" transform="rotate(135, 90, 75)"/>