javascriptsvggsap

Circle Not Following SVG Path Correctly


I generated the SVG using Illustrator and am trying to add animation using the gsap lib.

I want to move the circle along the path, but it’s not aligning properly. I’m not sure where I’m going wrong.

gsap.to("#c1", {
  motionPath: "#path1",
  duration: 20,
  ease: "none",
  repeat: -1
});
<svg viewBox="0 0 820 400" style="background-color: black;">
  <path stroke="green" id="path1" class="st1"
d="M113.44,47.01c10.18,2.21,29.71,8.81,40.9,22.37,21.44,25.99,4.39,57.68,20,83.87,8.48,14.22,28.92,30.73,85,32.75" />
  <circle id="c1" r="2" cx="-5" cy="-5" fill="red" />
</svg>

<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/MotionPathPlugin.min.js"></script>


Solution

  • <svg viewBox="0 0 240 80" style="background:beige">
    
      <!-- define path #road -->
      <path id="road" stroke="grey" fill="none" d="m40 40c0 100 160-100 160 0s-160-100-160 0z"/>
    
      <!-- define rect to be animated -->
      <rect x="-6" y="-3" width="12" height="6" fill="red" visibility="hidden">
      
        <!-- change *parent element* (rect) 'visibility' attribute -->
        <set attributeName="visibility" from="hidden" to="visible" begin="0.5s" />
        
        <!-- animate *parent element* (rect) over #road -->
        <animateMotion rotate="auto" begin="0s" dur="5s" repeatCount="indefinite">
           <mpath href="#road"/>
        </animateMotion>
        
      </rect>
    </svg>

    Alternative to visibility, use display:none

    <rect x="-6" y="-3" width="12" height="6" fill="red" display="none">
      <set attributeName="display" to="inline" begin="0.5s" />