I am trying to make my SVG animate while scrolling, which works however I cannot figure out how to make sure its contained in my browser view. Need to be able to see scrolling in real time
Heres my issue:
When my browser is full zoomed out, the scrolling animation works EXACTLY as I want it to:
https://imgur.com/a/1A5sTv4
When my browser is at 100% the animation does not work the same way:
https://imgur.com/a/QKk2r7Y
Heres my SVG:
<svg id="path" viewBox="0 0 1080 1195" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M0 0L949.322 446.411L187.627 745.034L1080 1195" stroke="#FF0000" stroke-width="5"/>
</svg>
Here is my JS as well:
// Get a reference to the <path>
let path = document.querySelector('path');
// Get length of path...
let pathLength = path.getTotalLength();
// 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;
// When the page scrolls...
let scrollAnimation = () => {
window.addEventListener("scroll", function(e) {
// What % down is it?
let scrollPercentage = (document.documentElement.scrollTop + document.body.scrollTop) / (document.documentElement.scrollHeight - document.documentElement.clientHeight);
// Length to offset the dashes
let drawLength = pathLength * scrollPercentage
// Draw in reverse
path.style.strokeDashoffset = pathLength - drawLength;
// ... 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;
}
});
}
scrollAnimation();
This is the tutorial i tried to follow while implementing my own needs:
https://css-tricks.com/scroll-drawing/
Any help here is greatly appreciated!