Skip to content Skip to sidebar Skip to footer

Moving Image On Scroll Through Svg Path

I want to move object through svg path on scroll=) I was trying to add parts of path on scroll into path, but it still doesn't work. Help!!!=) https://jsfiddle.net/YuriiBielozertse

Solution 1:

Something like this?

How this works:

  1. When we get a scroll event we:
  2. Calculate how far down the page we are
  3. Convert this percentage to a position on the path using the <path> element functions getTotalLength() and getPointAtLength().
  4. Reposition the dot so that it appears at this point.

functionpositionTheDot() {

  // What percentage down the page are we? var scrollPercentage = (document.documentElement.scrollTop + document.body.scrollTop) / (document.documentElement.scrollHeight - document.documentElement.clientHeight);

  // Get path lengthvar path = document.getElementById("theMotionPath");
  var pathLen = path.getTotalLength();
  
  // Get the position of a point at <scrollPercentage> along the path.var pt = path.getPointAtLength(scrollPercentage * pathLen);
  
  // Position the red dot at this pointvar dot = document.getElementById("dot");
  dot.setAttribute("transform", "translate("+ pt.x + "," + pt.y + ")");
  
};

// Update dot position when we get a scroll event.window.addEventListener("scroll", positionTheDot);

// Set the initial position of the dot.positionTheDot();
.verylong {
  height: 2000px;
}

svg {
  position: fixed;
  width: 200px;
  height: 200px;
}
<svgviewBox="0 0 120 120"xmlns="http://www.w3.org/2000/svg"version="1.1"xmlns:xlink="http://www.w3.org/1999/xlink"><!-- Draw the outline of the motion path in grey, along with 2 small circles at key points --><pathd="M10,110 A120,120 -45 0,1 110 10 A120,120 -45 0,1 10,110"stroke="green"stroke-width="2"fill="none"id="theMotionPath"/><circlecx="10"cy="110"r="3"fill="#000"/><circlecx="110"cy="10"r="3"fill="#000"/><!-- Red circle which will be moved along the motion path. --><circlecx="0"cy="0"r="5"fill="red"id="dot"/></svg><divclass="verylong"></div>

Post a Comment for "Moving Image On Scroll Through Svg Path"