Benji
Benji

Reputation: 807

Drawing Curved (Responsive) SVG Path on Scroll

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.

Upvotes: 2

Views: 4370

Answers (1)

Paul LeBeau
Paul LeBeau

Reputation: 101800

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.

Upvotes: 4

Related Questions