详细介绍SVG的translate平移变换,学习如何移动图形元素的位置。通过实例掌握平移变换的各种应用技巧。 translate变换将元素从当前位置移动到新位置,是最常用的变换之一。
transform="translate(tx, ty)"
<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)"/>
<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动画可以实现平滑的平移效果。
<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"/>