Lab Notebook

Path Along a Path

Demo

Open demo

Make a shape go around a path. In theory this could have been done easier with CSS, but I was curious if I could just load a SVG path and get points from it.

<script>
    my_path="M1005.05,1270.15C1005.05,1270.15 982.121,656.156 1178.97,656.156C1375.81,656.156 1296.24,1185.38 1323.9,1299.76C1351.57,1414.14 1654.37,1488.61 1728.57,1285.41C1791.71,1112.49 1665.87,620.875 1888.72,633.373C2087.96,644.547 2229.41,1799.24 1481.39,1804.44C964.029,1808.04 1005.05,1270.15 1005.05,1270.15Z"

    // load the path
   const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
   pathEl = document.createElementNS('http://www.w3.org/2000/svg', 'path');
   pathEl.setAttribute('d', my_path);
   svg.appendChild(pathEl);

   // Get total length of the Path
   totalLength = pathEl.getTotalLength();
   console.log("len:", totalLength);

    const canvas = document.getElementById('canvas');
    const ctx = canvas.getContext('2d');
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.strokeStyle = 'blue';
    ctx.lineWidth = 2;

    for (t=0; t < 1; t+=.01) {
   const clamped = Math.max(0, Math.min(1, t));

   // get the point on the path
   const pt = pathEl.getPointAtLength(clamped * totalLength);
   console.log(  pt.x, pt.y );


    ctx.ellipse(pt.x, pt.y, 80, 40, Math.PI / 4, 0, Math.PI * 2);
    }

    ctx.stroke();
</script>