Прокручиваемая SVG-линия

by vovkasolovev

HTML

<!DOCTYPE html>
<html lang="ru">
<head>
  <meta charset="UTF-8">
  <title>SVG Scroll Draw</title>
  <style>
    body {
      margin: 0;
      height: 5000px; /* чтобы была прокрутка */
    }

    svg {
      width: 100%;
      height: 3000px;
      display: block;
      background: #fff;
    }

    path {
      fill: none;
      stroke: #0077ff;
      stroke-width: 4;
      stroke-dasharray: 10000;
      stroke-dashoffset: 10000;
    }
  </style>
</head>
<body>

<svg viewBox="0 0 1920 3000" preserveAspectRatio="none">
  <path id="animatedPath"
        d="
          M 0 0
          C 200 100, 200 200, 0 300        <!-- петля -->
          C -200 400, -200 500, 0 600      <!-- вторая половина петли -->

          C 400 1000, 800 1400, 1200 1800  <!-- синус 1 -->
          C 1560 2200, 1800 2600, 1920 3000  <!-- синус 2 -->
        " />
</svg>

<script>
  const path = document.getElementById('animatedPath');
  const length = path.getTotalLength();

  path.style.strokeDasharray = length;
  path.style.strokeDashoffset = length;

  window.addEventListener('scroll', () => {
    const scrollTop = window.scrollY;
    const docHeight = document.documentElement.scrollHeight - window.innerHeight;
    const scrollPercent = scrollTop / docHeight;
    const drawLength = length * scrollPercent;
    path.style.strokeDashoffset = length - drawLength;
  });
</script>

</body>
</html>