translate 平移

详细介绍SVG的translate平移变换,学习如何移动图形元素的位置。通过实例掌握平移变换的各种应用技巧。 translate变换将元素从当前位置移动到新位置,是最常用的变换之一。

基本语法

transform="translate(tx, ty)"
  • tx:X轴方向的移动距离
  • ty:Y轴方向的移动距离(可选,默认为0)

基本平移

单轴平移

原始位置 X轴平移80
<rect x="20" y="50" width="50" height="30" fill="#3498db" opacity="0.3"/>
<rect x="20" y="50" width="50" height="30" fill="#3498db" transform="translate(80)"/>

双轴平移

原始 translate(100, 50)
<rect x="20" y="20" width="50" height="30" fill="#3498db" opacity="0.3"/>
<rect x="20" y="20" width="50" height="30" fill="#3498db" transform="translate(100, 50)"/>

负值平移

平移值可以是负数,表示向相反方向移动。

原始位置 负值平移
<rect x="150" y="50" width="50" height="30" fill="#3498db" opacity="0.3"/>
<rect x="150" y="50" width="50" height="30" fill="#e74c3c" transform="translate(-100, 30)"/>

多元素平移

对组元素应用平移可以同时移动多个元素。

组合 组合 组元素整体平移
<g transform="translate(50, 30)">
  <rect x="0" y="0" width="60" height="40" fill="#3498db"/>
  <text x="30" y="25" text-anchor="middle" fill="white" font-size="12">组合</text>
</g>

<g transform="translate(150, 30)">
  <rect x="0" y="0" width="60" height="40" fill="#e74c3c"/>
  <text x="30" y="25" text-anchor="middle" fill="white" font-size="12">组合</text>
</g>

实用案例

图标网格

<defs>
  <rect id="icon" width="40" height="40" rx="5"/>
</defs>

<use href="#icon" x="30" y="20" fill="#3498db"/>
<use href="#icon" x="30" y="20" fill="#e74c3c" transform="translate(50)"/>
<use href="#icon" x="30" y="20" fill="#2ecc71" transform="translate(100)"/>
<use href="#icon" x="30" y="20" fill="#f39c12" transform="translate(150)"/>

居中定位

元素居中定位
<rect x="0" y="0" width="100" height="60" fill="#3498db" transform="translate(100, 45)"/>

<line x1="150" y1="0" x2="150" y2="150" stroke="#e74c3c" stroke-width="1" stroke-dasharray="5,5"/>
<line x1="0" y1="75" x2="300" y2="75" stroke="#e74c3c" stroke-width="1" stroke-dasharray="5,5"/>

重复图案

平移创建重复图案
<defs>
  <circle id="dot" r="10" fill="#3498db"/>
</defs>

<use href="#dot" cx="30" cy="50"/>
<use href="#dot" cx="30" cy="50" transform="translate(40)"/>
<use href="#dot" cx="30" cy="50" transform="translate(80)"/>
<use href="#dot" cx="30" cy="50" transform="translate(120)"/>

CSS动画平移

使用CSS动画可以实现平滑的平移效果。

CSS动画平移
<style>
  .move-anim {
    animation: moveX 2s ease-in-out infinite alternate;
  }
  @keyframes moveX {
    from { transform: translateX(20px); }
    to { transform: translateX(220px); }
  }
</style>

<circle cx="0" cy="50" r="20" fill="#3498db" class="move-anim"/>

注意事项

  1. 相对移动:translate是相对于元素原始位置移动
  2. 不影响布局:变换不会影响其他元素的布局
  3. 坐标系:平移会改变元素的坐标系
  4. 性能:translate变换性能较好,适合动画