Who doesn’t like a good SVG animation? SVGs are so nice to work with because they can scale up or down infinitely without getting pixelated. If you’re looking to implement SVG scroll drawing in your current or future projects, this short post will provide 8 easy steps to do just that.
Follow along with this codepen to see the animation in action.
Step 2: Wrap your SVG in a div.
Step 3: Update your SVG path with the following fill, stroke, stroke-width, and id attributes:
Step 4: Give your containing div a height so that it is large enough to create a vertical scroll. I did this because my SVG was the only element on the page. If you have lots of other content on the page, this step isn’t necessary, as long as the elements are in the same containing div.
Step 5: Apply a fixed position to your SVG element so that as you scroll down the page, the SVG stays put in the viewport.
Step 6: Get the length of the SVG path. This value is important for the next step.
Step 7: Apply strokeDasharray and strokeDashoffset styles to your SVG. These two properties are the key players in animating an SVG. By setting them to the full length of the SVG path, we are ensuring that no dashes are visible on the path as it appears.
Step 8: For the final step, add an event listener when the window begins to scroll. In the event listener, offset the dash by the same amount as the percentage scrolled.
That’s it! When I was learning, this post from CSS Tricks really helped me so check it out if you need another explanation.
SVG animations can really increase the interest on a website. Like anything, they must be used sparingly to avoid confusion or distraction. This applies to SVG scroll drawing in particular. SVG scroll drawing can either take up a small section of the webpage, or the animation can follow the user all the way down the page. When used correctly, this unique animation technique can delight the user, giving them a sense that they have control over the animations. Go ahead, try it out!