Ali Boukeroui 2 min read
How To Draw On Scroll Using Javascript
According to Jake Archibald's excellent technique where an SVG path is animated to look like it’s drawing itself. He has a very good blog post on how to work.
It's a clever trick to use dash lines, but the gap in the dash is too long to cover it all the way. Then you can move it in such a way that it covers the whole path again, making it look like it is drawing itself.
Using a little bit of JavaScript, we can draw the shape until it's finished as the page scrolls down.
This Is a Simple Scroll Drawing Demo
5 Steps To Draw On Scroll Using Javascript
-
Step 1 : Get the SVG Path
The SVG It has to be a
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100.6 107.6" id="star-svg"> <path id="frontendor-path" fill="none" stroke="white" stroke-width="2" d=" ... " /> </svg>
-
Step 2 : Find The Length Of The SVG Path
// Get a reference to the <path>
var path = document.querySelector('#frontendor-path');
// Get length of path... ~577px in this demo
var pathLength = path.getTotalLength();
-
Step 3 : Hide The SVG Shape By Offsetting Dash
// Make very long dashes (the length of the path itself)
path.style.strokeDasharray = pathLength + ' ' + pathLength;
// Offset the dashes so the it appears hidden entirely
path.style.strokeDashoffset = pathLength;
-
Step 4 : When The Page Scrolls, Offset Dash Same Amount As % Scrolled
// When the page scrolls...
window.addEventListener("scroll", function(e) {
// What % down is it?
var scrollPercentage = (document.documentElement.scrollTop + document.body.scrollTop) / (document.documentElement.scrollHeight - document.documentElement.clientHeight);
// Length to offset the dashes
var drawLength = pathLength * scrollPercentage;
// Draw in reverse
path.style.strokeDashoffset = pathLength - drawLength;
});
-
Step 5 : Remove Dashing After Scrolling To Bottom
// ... at bottom of scrolling function
// When complete, remove the dash array, otherwise shape isn't quite sharp
if (scrollPercentage >= 0.99) {
path.style.strokeDasharray = "none";
} else {
path.style.strokeDasharray = pathLength + ' ' + pathLength;
}
Awesome! This is all you need to draw any SVG shape using these 5 simple steps.