变换

全面介绍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()函数将元素绕指定点旋转。

绕原点旋转30° 绕中心旋转45°
<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()函数改变元素的大小。

放大1.5倍 缩小0.5倍
<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轴倾斜元素。

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)"/>

注意事项

  1. 变换顺序:多个变换按书写顺序依次执行
  2. 坐标系:变换是相对于当前坐标系进行的
  3. 原点:默认变换原点是当前用户坐标系的原点(0,0)
  4. 累积效果:嵌套元素的变换会累积