How To Draw A Scroll Easy
We've taken an in-depth expect at how SVG line drawing works before. It's a clever trick where you use dashed lines for the stroke, but the gap in the dash is so long it covers the entire path. Then you can move it such that it covers the unabridged path again, which makes it appear as if it's drawing itself.
Using a bit of JavaScript, we can become a niggling fancier, drawing the shape to completion as folio is scrolled to the bottom.
Demo
See the Pen Scroll Drawing by Chris Coyier (@chriscoyier) on CodePen.
Step 1: Go a <path>
It has to be a <path>. Any other kind of SVG chemical element won't work (e.g. <rect>). You lot tin force elements to exist paths though. I have a Lodge video on this. Y'all may need to resort to trickery like adding an additional vector indicate along an already straight edge.
In my demo here, I just copy-and-pasted the shape right out of Illustrator.
Give the path an ID if it doesn't accept one:
<svg xmlns="http://world wide web.w3.org/2000/svg" viewBox="0 0 100.6 107.vi" id="star-svg"> <path id="star-path" fill="none" stroke="black" stroke-width="two" d=" ... " /> </svg> Step 2: Find length of that path
// Get a reference to the <path> var path = document.querySelector('#star-path'); // Get length of path... ~577px in this demo var pathLength = path.getTotalLength(); Step three: Hide shape by offsetting dash
// Make very long dashes (the length of the path itself) path.fashion.strokeDasharray = pathLength + ' ' + pathLength; // Offset the dashes so the it appears hidden entirely path.style.strokeDashoffset = pathLength; Pace 4: When page scrolls, offset dash same corporeality as % scrolled
// When the page scrolls... window.addEventListener("whorl", role(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 contrary path.style.strokeDashoffset = pathLength - drawLength; }); Stride 5: If scrolled to bottom, remove dashing
If you don't practice this, the shape doesn't await quite every bit neatly/sharply finished as if you lot didn't applying whatsoever dashing at all.
I'm not certain why. I don't think you can fiddle with the numbers to set up it. Just it'south like shooting fish in a barrel plenty to remove.
// ... at lesser of scrolling function // When complete, remove the dash assortment, otherwise shape isn't quite precipitous if (scrollPercentage >= 0.99) { path.style.strokeDasharray = "none"; } else { path.fashion.strokeDasharray = pathLength + ' ' + pathLength; } The 0.99 is to account for fuzzy math. Sometimes yous don't get a perfect i.0 from the division.
See a full page demo.
Source: https://css-tricks.com/scroll-drawing/
Posted by: brownthisees.blogspot.com

0 Response to "How To Draw A Scroll Easy"
Post a Comment