How to Draw on Scroll using JavaScript and SVG ?

To create an engaging scroll animation, use JavaScript to manipulate SVG path properties. As the user scrolls, JavaScript calculates the scroll percentage and adjusts the strokeDasharray and strokeDashoffset of the SVG path, gradually drawing the path to create a dynamic visual effect.

Approach

  • Create an HTML file (index.html) and define the basic structure. The <svg> element contains a <path> element. This SVG displays a zigzag line using specific coordinates for the d attribute.
  • The CSS sets the body height to 2000px to enable scrolling, centers the SVG on the page, and styles the path with a steel blue stroke color, a width of 2px, and no fill.
  • The SVG is configured to have a viewBox of “0 0 100 100″ and uses preserveAspectRatio=”none” to ensure the aspect ratio is not preserved, allowing it to stretch as needed.
  • The JavaScript code listens for the scroll event and dynamically updates the SVG path’s stroke length. It calculates the scroll percentage and adjusts the strokeDasharray and strokeDashoffset properties to animate the drawing of the path as the user scrolls.
  • The strokeDasharray property defines the pattern of dashes and gaps used to paint the outline of the shape, while strokeDashoffset specifies where the dash pattern starts. This creates the effect of the path being drawn as the user scrolls down the page, and reverses the drawing when scrolling up.

Example: The example below shows how to draw on scroll using JavaScript and SVG.

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" 
          content="width=device-width, initial-scale=1.0">
    <title>SVG Scroll Animation</title>
    <style>
        body {
            height: 2000px;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        svg {
            width: 100%;
            height: 300px;
        }

        path {
            stroke: steelblue;
            stroke-width: 2;
            fill: none;
        }
    </style>
</head>

<body>
    <svg viewBox="0 0 100 100" 
         preserveAspectRatio="none">
        <path id="zigzag" d="M10 90 L30 10 
                             L50 90 L70 10 L90 90" />
    </svg>
    <script src="script.js"></script>
</body>

</html>
JavaScript
window.addEventListener('scroll', function () {
    let scrollTop = window.pageYOffset || 
                    document.documentElement.scrollTop;
    let path = document.getElementById('zigzag');
    let pathLength = path.getTotalLength();

    // Calculate the scroll percentage
    let scrollPercent = scrollTop / 
        (document.documentElement.scrollHeight - window.innerHeight);

    // Calculate the length to be drawn based on scroll percentage
    let drawLength = pathLength * scrollPercent;

    // Update the dasharray and dashoffset
    path.style.strokeDasharray = pathLength;
    path.style.strokeDashoffset = pathLength - drawLength;

    // Reverse the drawing when scrolling up
    if (scrollTop === 0) {
        path.style.strokeDashoffset = pathLength;
    }
});

Output: