【问题标题】:svg animateMotion is offset from pathsvg animateMotion 从路径偏移
【发布时间】:2019-10-20 19:10:08
【问题描述】:

我有这个 svg:

我的目标是让盒子在保持旋转的同时沿着路径移动。为了实现这一点,我在正方形中添加了一个<animateMotion /> 元素,其路径与圆形相同。 (演示here)。圆和 animateMotion 的路径都以 M 开头,据我所知,它表示 SVG 中的绝对位置。出于某种原因,尽管正方形旋转了 90 度并且正在圆外移动(同时仍遵循圆形路径)。

<svg width="133" height="131" viewBox="0 0 266 131"  fill="none" xmlns="http://www.w3.org/2000/svg">
  <path d="M102.242 63.2475C102.242 43.3399 86.105 27.202 66.197 27.202C46.2889 27.202 30.151 43.3399 30.151 63.2475C30.151 83.154 46.2889 99.2939 66.1965 99.2939C86.105 99.2939 102.243 83.154 102.243 63.248" stroke="#00F" stroke-width="1"/>
  
  <path d="M95.0596 24.2323L79.2727 43.3838L73.0606 38.2323L88.8177 19.0823L95.0601 24.2333" fill="red">
      <animateMotion
    path="M102.242 63.2475C102.242 43.3399 86.105 27.202 66.197 27.202C46.2889 27.202 30.151 43.3399 30.151 63.2475C30.151 83.154 46.2889 99.2939 66.1965 99.2939C86.105 99.2939 102.243 83.154 102.243 63.248"
    rotate="auto"
    dur="6s" repeatCount="indefinite" fill="freeze"/>
  </path>
</svg>

我怎样才能让它工作,为什么它不工作?

【问题讨论】:

  • 动画运动是对路径的附加变换,被变换的路径不在原点。

标签: html css svg


【解决方案1】:

您需要调整要旋转的对象的路径,使其尽可能靠近 SVG 的 (0,0) 点(原点)以避免平移效果。

这是对象跟随路径的近似值。仍然不完美,所以我应用旋转来纠正最终位置。我还考虑过使用&lt;mpath /&gt; 来避免重复同一路径两次:

svg {
  border:1px solid;
}
<svg width="133" height="131" viewBox="0 0 133 131"  fill="none" xmlns="http://www.w3.org/2000/svg">
  <path d="M102.242 63.2475C102.242 43.3399 86.105 27.202 66.197 27.202C46.2889 27.202 30.151 43.3399 30.151 63.2475C30.151 83.154 46.2889 99.2939 66.1965 99.2939C86.105 99.2939 102.243 83.154 102.243 63.248" stroke="#00F" stroke-width="1" id="path"/>
  
  <path d="M21.0596 -13.7677 L5.2727 5.3838 L-0.9394 0.2323 L14.8177 -18.9177 L21.0601 -13.7667" fill="red" transform="rotate(-50,10,20)">
     <animateMotion 
    dur="6s" repeatCount="indefinite" fill="freeze" rotate="auto-reverse">
      <mpath xlink:href="#path"/>
    </animateMotion>
  </path>
</svg>

因为它是一个矩形,你可以简化如下:

svg {
  border:1px solid;
}
<svg width="133" height="131" viewBox="0 0 133 131"  fill="none" xmlns="http://www.w3.org/2000/svg">
  <path d="M102.242 63.2475C102.242 43.3399 86.105 27.202 66.197 27.202C46.2889 27.202 30.151 43.3399 30.151 63.2475C30.151 83.154 46.2889 99.2939 66.1965 99.2939C86.105 99.2939 102.243 83.154 102.243 63.248" stroke="#00F" stroke-width="1" id="path"/>
  

  <rect x="-5" y="-15" width="10" height="30" fill="red" >
     <animateMotion 
    dur="6s" repeatCount="indefinite" fill="freeze" rotate="auto">
      <mpath xlink:href="#path"/>
    </animateMotion>
  </rect>
</svg>

【讨论】:

  • 谢谢!有什么方法可以以编程方式执行您在步骤 1 中所做的转换?我通常只得到 svg,然后我的应用需要添加动作。
  • @cubefox 您可以随时应用翻译将元素放回原点,如下所示:jsfiddle.net/gstencp5/1
  • @TemaniAfif 它适用于矩形但不适用于路径,我的形状非常复杂
猜你喜欢
  • 2021-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-18
  • 2019-04-24
  • 1970-01-01
  • 1970-01-01
  • 2022-01-12
相关资源
最近更新 更多