SVG getPointAtLength demo

Demo showing how to make a circle follow an SVG path.

by dm89

HTML

<input type="range" min=0 max=10 step="5">
<svg
   xmlns="http://www.w3.org/2000/svg"
   width="640"
   height="480"
   version="1.1"
   id="svg" viewBox="0 0 640.00001 480.00001">
        <g
     id="g4215"
     transform="matrix(0.95349969,0.47631258,-0.95349969,0.47631258,223.67401,-10.989474)">
    <path
       style="opacity:1;fill:none;fill-opacity:1;stroke:#ff0000;stroke-width:1.04924929;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1"
       d="M 309.04502,273 A 6.0450234,6.0450234 0 0 1 303,279.04502 6.0450234,6.0450234 0 0 1 296.95498,273 6.0450234,6.0450234 0 0 1 303,266.95498 6.0450234,6.0450234 0 0 1 309.04502,273 Z"
       id="orbit-earth"
       inkscape:connector-curvature="0" />
    <path
       style="opacity:1;fill:none;fill-opacity:1;stroke:#ff0000;stroke-width:1.04924929;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1"
       d="M 331.79015,273 A 28.790121,28.790121 0 0 1 303.00003,301.79012 28.790121,28.790121 0 0 1 274.20991,273 28.790121,28.790121 0 0 1 303.00003,244.20988 28.790121,28.790121 0 0 1 331.79015,273 Z"
       id="orbit-jupiter"
       inkscape:connector-curvature="0" />
    <path
       style="opacity:1;fill:none;fill-opacity:1;stroke:#ff0000;stroke-width:1.04924929;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1"
       d="M 544.49097,236.3987 A 215.34717,215.34717 0 0 1 329.1438,451.74586 215.34717,215.34717 0 0 1 113.79663,236.3987 215.34717,215.34717 0 0 1 329.1438,21.051529 215.34717,215.34717 0 0 1 544.49097,236.3987 Z"
       id="orbit-pluto"
       inkscape:connector-curvature="0" />
    <path
       inkscape:connector-curvature="0"
       id="path-newhorizons"
       d="m 299.03921,268.38562 c -9.15032,12.02614 -6.27451,30.71895 -6.27451,30.71895 l 122.90977,272.83728"
       style="fill:none;fill-rule:evenodd;stroke:#ff0000;stroke-width:1.04924929px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" />
    <rect
    ...

JavaScript

var path = document.querySelector('#path-newhorizons');
var range = document.querySelector('input');
var circle = document.querySelector('#newhorizons')

console.log(path.getTotalLength());
range.setAttribute('max', path.getTotalLength());
range.setAttribute('step', path.getTotalLength()/100);

range.addEventListener('input', function(e){
    var pos = path.getPointAtLength(e.srcElement.value);
    circle.setAttribute('cx', pos.x);
    circle.setAttribute('cy', pos.y);
    console.log(circle, pos);
});