Drawing Curved (Responsive) SVG Path on Scroll

2019-07-18 14:56发布

After reading up on all of the buzz around animating SVGs with the strokeDashArray trick I finally found a little bit of code to connect this functionality to the user's scroll position on the Cable Codes blog.

This idea is great, but I have a wavy, curvy path that actually loops at one point. So I divided the calculated total length of the path to get a good middle ground but it still falls short with the line lagging behind or getting ahead as you scroll.

Here's an example of the snippet with some adjustments:

$(document).ready(function(){

  $(window).scroll(function() {
    drawLine( $('#route'), document.getElementById('path') );
  });

  //draw the line
  function drawLine(container, line){

    var pathLength = line.getTotalLength(),
        distanceFromTop = container.offset().top - $(window).scrollTop(),
        percentDone = 1 - (distanceFromTop / $(window).height()),
        length = percentDone * pathLength / 30;

    line.style.strokeDasharray = [ length ,pathLength].join(' ');
  }

});

I made a CodePen with the path and the snippet of code with my adjustments. Any ideas as to how I could keep the end of this line in the centre of the viewport as the user scrolls?

Updated: The SVG is, in fact, responsive. This changes a few things, eh? Here's an updated CodePen.

1条回答
Root(大扎)
2楼-- · 2019-07-18 15:17

The way you calculated your percent scroll was a bit off. I have made a working version here:

http://codepen.io/anon/pen/idvoh

You need to work out the maximum value of scrolltop by subtracting the window height from the document height.

As for how you stop it getting ahead or falling behind when the line twists and turns a lot. You need to space out your line segments at regular heights. So, for example, if your line consists of 10 beziers, make sure they start at (approximately) n/10ths of the height of the line. That should keep the pacing about right.

查看更多
登录 后发表回答