)
}
}
)
(
}
{
)
)
(
)
(
(
{
}
)
(
)
}
)
)
{
(
(
)
)
}
)
(
}

Animation Along Path SVG

  1. const el = document.body.appendChild(
  2.   document.createElement('div'));
  3.  
  4. el.innerHTML = `
  5.   <svg width="100%" height="100%" viewBox="0 0 550 496">
  6.     <path 
  7.       d="M 20 10 C 100 100 300 00 300 100 200 200 150 300 20 10" 
  8.       stroke="black" fill='none' vector-effect="non-scaling-stroke"/>
  9.     <circle cx="20" cy="10" r="6" fill="red" />
  10.   </svg>
  11.   <style>
  12.     svg, div, body, html {
  13.       overflow: visible; 
  14.       height: 100%; 
  15.       width: 100%;
  16.       margin: 0; padding: 0;
  17.     }
  18.   </style>
  19.  `;
  20.  
  21. const circle = el.querySelector('circle');
  22. const path = el.querySelector('path');
  23. const length = path.getTotalLength();
  24. let pos = 0;
  25.  
  26. function loop() {
  27.   pos += 3;
  28.   if (pos > length) {
  29.     pos = 0;
  30.   }
  31.   const point = path.getPointAtLength(pos);
  32.   circle.cx.baseVal.value = point.x;
  33.   circle.cy.baseVal.value = point.y;
  34.   requestAnimationFrame(loop);
  35. }
  36. loop();

SVG has an easy way to animate something along an arbitrary path… getPointAtLength

snippet.zone ~ 2021-24 /// {s/z}