Search code examples
csssvgsvg-animate

How to make an SVG object follow a path correctly using SMIL


I am trying t create a simple SVG animation(using SMIL) and I can't seem to figure out why the orb isn't following the arc, instead the orb it is at the bottom of the page. Here is my code:

<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
     viewBox="0 0 1240 768" style="enable-background:new 0 0 1240 768;" xml:space="preserve">


<style type="text/css">
    .st0{fill:#FFFFFF;}
    .st1{fill:#0FBA70;}
</style>
<animateMotion xlink:href="#orb" dur="10s" begin="0s" fill="freeze" repeatCount="indefinite">
    <mpath xlink:href="#motionPath" />
</animateMotion>
<g>
    <polygon class="st0" points="389.5,405.5 394,405.5 926.8,400.5 930.5,400.5  "/>
    <path id="motionPath" d="M390.9,407.5l-2.9-4.1C426,377,625,248.9,820.4,327.2c40.5,16.2,78.1,40.3,111.8,71.5l-3.4,3.7
        c-33.2-30.8-70.3-54.5-110.2-70.5C625.5,254.5,428.5,381.3,390.9,407.5z"/>
</g>
<g>
    <circle id="orb" class="st1" cx="389.5" cy="400.5" r="56.5"/>
</g>
</svg>


Solution

  • The orb is currently being offset with the cx and cy values:

    <circle id="orb" class="st1" cx="389.5" cy="400.5" r="56.5"/>
    

    If you remove those values, the orb follows the path:

    <circle id="orb" class="st1" r="56.5"/>
    

    See https://developer.mozilla.org/en-US/docs/Web/SVG/Element/animateMotion for a working example, and if you open that in JSFiddle or Codepen and add a cx or cy value you will observe the same behavior (circle is animating offset from the path).

    .st0 {
      fill: #FFFFFF;
    }
    
    .st1 {
      fill: #0FBA70;
    }
    <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 1240 768" style="enable-background:new 0 0 1240 768;" xml:space="preserve">
    <animateMotion xlink:href="#orb" dur="10s" begin="0s" fill="freeze" repeatCount="indefinite">
        <mpath xlink:href="#motionPath" />
    </animateMotion>
    <g>
        <polygon class="st0" points="389.5,405.5 394,405.5 926.8,400.5 930.5,400.5  "/>
        <path id="motionPath" d="M390.9,407.5l-2.9-4.1C426,377,625,248.9,820.4,327.2c40.5,16.2,78.1,40.3,111.8,71.5l-3.4,3.7
            c-33.2-30.8-70.3-54.5-110.2-70.5C625.5,254.5,428.5,381.3,390.9,407.5z"/>
    </g>
    <g>
        <circle id="orb" class="st1" r="56.5"/>
    </g>
    </svg>