Skip to content
Advertisement

updating SVG animateMotion path using JavaScript

I try changing an SVG motion path according to a html select value using JS. The path updates as expected, but the element, which uses the path as a motion path continues to move along the original path. What am I missing?

function changepath(selectObject) {
  let value = selectObject.value;
     let path = document.getElementById("planePath");
     let plane = document.getElementById("animPath");
    
     let rotation = "rotate(" + value + ")";
     path.setAttribute("transform", rotation);
     plane.setAttribute("transform", rotation);
}
body {
 background: #eee;
}

.planePath {
    opacity: 0.8;
 stroke: darkslategrey;
 stroke-width: 2px;
 fill: none;
}

.plane {
    transform: scale(0.15);
}

select {
    margin-left: 2em;;
}
<svg viewBox="0 0 2000 200">
<!--    <path class="planePath" id="planePath" d="M 0 0 C 200 250 250 50 550 150 C 850 250 700 180 1000 200 " /> -->
        <path class="planePath" id="planePath" d="M 50 100 c 14 -3 736 -115 1900 0" />
    <g id="plane" class="plane">
    <rect x="0" y="0" width="100" height="100"/>
 </g>
 <animateMotion xlink:href="#plane" dur="6s" repeatCount="indefinite" rotate="auto">
  <mpath id="animPath" xlink:href="#planePath" />
    </animateMotion>
</svg>

<select name="route" id="route" onchange="changepath(this)">
     <option value="0">0°</option>
  <option value="1">1°</option>
  <option value="2">2°</option>
  <option value="3">3°</option>
  <option value="4">4°</option>
</select>

Advertisement

Answer

As Danny mentioned in his answer the mpath is using the untransformed path. If you need it to be transformed you can wrap both the path and the animated rect in a group and transform the group.

<svg viewBox="0 0 2000 200">
 <g transform="rotate(5)">
  <path id="path" fill="none" stroke="red" stroke-width="5" 
        d="M 50 100 c 14 -3 736 -115 1900 0" />
  <rect id="block" x="0" y="0" width="20" height="20"/>
  <animateMotion href="#block" dur="2s" repeatCount="indefinite" 
                 rotate="auto" restart="always">
    <mpath href="#path" />
  </animateMotion>
 </g>
</svg>
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement