首页 > 解决方案 > svg 动画在移动过程中旋转

问题描述

我做了以下演示:

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">
<animate xlink:href="#star" attributeName="d" attributeType="XML" begin="0s" dur="2s" repeatCount="1" values="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;M300 210 L322.45 269.1 L385.6 272.19 L336.33 311.8 L352.9 372.81 L300 338.2 L247.1 372.81 L263.67 311.8 L214.4 272.19 L277.55 269.1Z;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"></animate>
<animateTransform xlink:href="#star" attributeName="transform" attributeType="XML" type="rotate" from="0 100 100" to="360 100 100" dur="2s" begin="0s" repeatCount="None" fill="freeze"></animateTransform>
  </path>
</svg>

我期待星星在旋转时沿直线移动。但是,添加旋转动画改变了移动路径。

我正在寻找一个 svg 动画标签解决方案,而不是一个 css 解决方案


非常感谢

标签: htmlxmlanimationsvg

解决方案


这就是我的做法:不是为星星的 d 属性设置动画,而是使用 animate 将星星翻译到新位置。为了使两个动画一起工作,我将additive="sum"用于第二个动画。

svg{width:90vh}
<svg viewBox="0 0 500 500" 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" attributeType="XML" type="translate" to="300 300" dur="2s" begin="0s" repeatCount="1" fill="freeze" ></animateTransform>
    
    <animateTransform attributeName="transform" attributeType="XML" type="rotate" from="0 99.6 91.4" to="360 99.6 91.4" dur="2s" begin="0s" repeatCount="1" fill="freeze" additive="sum"></animateTransform>
      </path>
    </svg>


推荐阅读