Search code examples
javascriptstroke-dasharray

Scroll listener stroke dashoffset draw SVG between range of pixels?


I'm having a really hard time with this so I wanted to see if anyone here would be able to help me think through this.

I'm attempting to attach a scroll listener to an SVG path between a specific pixel range, so it will draw back and forth when you scroll up and down.

I've been researching this a few days and I've found topics on converting the stroke dashoffset progress to a percentage based off of the top of the window or height of the document as a single number, but can't seem to wrap my noggin around how I would apply that same logic to a specified pixel range.

How I would have the stroke-dasharray of the svg path be at its starting value (3000) at the start of the range of pixels (say 2500px to 3000px from the top of the document.) and the end value of stroke dasharray be 6000 (it's end value) at the end of the pixel range? I really hope this isn't a stupidly easy issue I'm just staring at for too long. Here is what I have:

var path = document.querySelector('path');

var length = path.getTotalLength();

var triggerPadding = 600;

var startLocation = document.querySelector('.scroll-container').getBoundingClientRect()

var bodyRect = document.body.getBoundingClientRect();

var elemRect = document.querySelector('.scroll-container').getBoundingClientRect();

var elementYLocation = elemRect.top - bodyRect.top;

var elementBottomYLocation = Math.round((elemRect.bottom - bodyRect.top) - triggerPadding);

var startTrigger = Math.round(elementYLocation - triggerPadding);

path.style.strokeDasharray = length + ' ' + length;

path.style.strokeDashoffset = length;

// 

function animationScroll(currentY, startY, endY) {
    console.log({ currentY, startY, endY })
    if (currentY >= startY) {
        //do animation

    }
}

window.addEventListener('scroll', function () {
    const currentY = window.pageYOffset || window.scrollY;

    animationScroll(currentY, startTrigger, elementBottomYLocation);

}, false);

Any help at all on the equation I would need to do this would be so appreciated. Thank you in advance.


Solution

  • User @CBroe answers and provides/walks through the required formula to calculate a linear transformation of two number ranges.

    f(t) = c + ( (d - c) / (b - a) ) * (t - a);