You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在单一开放路径上实现SVG对象的起点到终点及返程移动?

Solution for Reversing Motion Along a Single Open Path in SVG

Hey there! To get your object traveling from start to end and back along the same open path without adding extra overlapping paths, you can use a simple tweak to your existing animateMotion element. Here's how to implement it smoothly:

Complete Working SVG Example

<?xml version="1.0"?>
<svg viewBox="0 0 120 120" xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink">
  <!-- Draw the motion path outline (grey line) -->
  <path d="M20,60 C40,20 80,100 100,60" stroke="#ccc" fill="none" stroke-width="2"/>
  
  <!-- Mark start and end points with small circles -->
  <circle cx="20" cy="60" r="3" fill="#000"/>
  <circle cx="100" cy="60" r="3" fill="#000"/>
  
  <!-- The moving object (red circle) -->
  <circle r="4" fill="#ff3333">
    <!-- Animation that goes forward then reverse -->
    <animateMotion
      path="M20,60 C40,20 80,100 100,60"
      dur="3s"                  <!-- Time for one direction (start → end) -->
      repeatCount="indefinite"  <!-- Loop back and forth continuously -->
      direction="alternate"     <!-- Reverse direction after each full path traversal -->
      rotate="auto"             <!-- Optional: keeps object facing along the path -->
    />
  </circle>
</svg>

Key Attribute Breakdown

  • path: Uses your original single open path—no duplicates needed here.
  • dur: Sets how long it takes to travel one way (start to end). The reverse trip will take the same amount of time, making a full round trip last dur * 2 seconds.
  • direction="alternate": This is the magic! It tells the animation to flip direction every time it finishes the path, so it automatically goes back to the start without extra code.
  • repeatCount="indefinite": Makes the back-and-forth motion loop forever. If you only want it to go once and stop, set this to 2 instead.
  • rotate="auto": Optional, but ensures your object stays oriented along the path as it moves (remove this if you don't need rotation).

For a One-Time Round Trip

If you want the object to go start→end→start once then stop, adjust the animation attributes like this:

<animateMotion
  path="M20,60 C40,20 80,100 100,60"
  dur="3s"
  repeatCount="2"
  direction="alternate"
  fill="freeze" <!-- Keeps the object at the start position when done -->
/>

This approach sticks strictly to your single path requirement and builds on the forward motion you already have. Hope this helps!

内容的提问来源于stack exchange,提问作者jay khatri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:38:47