SVG元素移动时添加旋转动画改变路径,求纯animate标签解决方案
问题原因
你当前的实现冲突点在于:修改d属性的位移动画和固定旋转中心的旋转动画不匹配。旋转动画全程以星星初始位置的中心点(100,100)为旋转圆心,当d属性修改将星星坐标整体偏移到右下角后,旋转圆心没有同步偏移,就会导致星星的移动轨迹发生偏移。
解决方案
通过多组animateTransform叠加实现边直线移动边旋转的效果,完全使用SVG原生动画标签实现,无需CSS方案:
svg{ width: 200px; height: 200px; } body{ position: fixed; margin: 0; padding: 0; width: 100vw; height: 100vh; display: flex; justify-content: center; align-items: center; }
<svg viewBox="0 0 400 400" xmlns="http://www.w3.org/2000/svg"> <path id="star" d="M100,10 L122.45,69.1 L185.6,72.19 L136.33,111.8 L152.9,172.81 L100,138.2 L47.1,172.81 L63.67,111.8 L14.4,72.19 L77.55,69.1Z" fill="gray" stroke="lightgreen" stroke-linejoin="round" stroke-linecap="round" stroke-width="15"> <!-- 平移动画,对应你原本的移动路径:原位→右下角→原位 --> <animateTransform attributeName="transform" type="translate" values="0 0;200 200;0 0" dur="2s" begin="0s" repeatCount="1" fill="freeze" additive="sum"> </animateTransform> <!-- 旋转动画,绕星星自身中心旋转360度 --> <animateTransform attributeName="transform" type="rotate" from="0 100 100" to="360 100 100" dur="2s" begin="0s" repeatCount="1" fill="freeze" additive="sum"> </animateTransform> </path> </svg>
实现逻辑
- 星星的
d属性固定为初始形态,不再通过修改路径坐标实现位移,避免旋转中心不匹配的问题 - 新增
type="translate"的位移动画,数值对应你需要的移动距离,和原有动画时长、循环逻辑完全对齐 - 两个
animateTransform都添加additive="sum"属性,保证平移和旋转效果叠加生效,不会互相覆盖 - 旋转始终以星星自身的几何中心为圆心,平移时整体位置同步移动,不会出现轨迹偏移
内容的提问来源于stack exchange,提问作者Weilory
相关产品推荐
相关产品推荐

