Search code examples
javascriptsvg

Animate a circle back and forth along a path


Hi I have a basic energy flow diagram as below

enter image description here

The Svg is here

How would I go about making the coloured circles move along the coloured paths ? I have tried using something like

<animateMotion
                        dur="10s"
                        repeatCount="indefinite"
                        path="m 281.66783,66.052163 c -58.15279,11.63055 -95.43899,64.652217 -95.43899,64.652217"
                    />

but that makes the yellow circle disappear. I also think that method does not allow for different directions.

I need to animate the circles so they go in both directions along their path and at different rates. Does this require javascript or can it be done in svg to keep the code minimal to activate the animations ?

Thanks for any guidance


Solution

  • Looks like you need (Arrays) keyPoints and keyTimes on <animateMotion> for positioning. (0=start 1=end)

    Add <animate> for other attribute settings.

    <svg viewBox="0 0 200 100">
        <path id="PATH" stroke="black" fill="none" d="M10 50H200" />
        <circle r="10" fill="red">
          <animateMotion dur="5s" keyPoints="0;1;0" keyTimes="0;.8;1" 
                         calcMode="linear" repeatCount="indefinite">
            <mpath href="#PATH" />
          </animateMotion>
          <animate 
             attributeName="fill"
             attributeType="XML"
             values="red;green;yellow;hotpink;blue"
             keyTimes= "0;0.4;0.6;0.8;1"
             dur="10s"
             repeatCount="indefinite"/>
          <animate 
             attributeName="r"
             attributeType="XML"
             values="10;15;10"
             keyTimes= "0;0.5;1"
             dur="1s"
             repeatCount="indefinite"/>
        </circle>
    </svg>