Как запустить анимацию прокрутки svg на указанной c части страницы - PullRequest
0 голосов
/ 04 апреля 2020

У меня есть простая SVG-анимация, которая происходит при прокрутке. Но как я могу заставить анимацию запускаться дальше вниз по странице?

Теперь она запускается сразу после начала прокрутки.

// Get the id of the <path> element and the length of <path>
var triangle = document.getElementById("triangle");
var length = triangle.getTotalLength();

// The start position of the drawing
triangle.style.strokeDasharray = length;

// Hide the triangle by offsetting dash. Remove this line to show the triangle before scroll draw
triangle.style.strokeDashoffset = length;

// Find scroll percentage on scroll (using cross-browser properties), and offset dash same amount as percentage scrolled
window.addEventListener("scroll", myFunction);

function myFunction() {
var scrollpercent = (document.body.scrollTop + document.documentElement.scrollTop) / (document.documentElement.scrollHeight - document.documentElement.clientHeight);

  var draw = length * scrollpercent;
  
  // Reverse the drawing (when scrolling upwards)
  triangle.style.strokeDashoffset = length - draw;
}
<h2>Scroll down this window to draw a triangle.</h2>
<p>Scroll back up to reverse the drawing.</p>

<svg id="mySVG">
  <path fill="none" stroke="red" stroke-width="3" id="triangle" d="M150 0 L75 200 L225 200 Z" />
  Sorry, your browser does not support inline SVG.
</svg>

1 Ответ

0 голосов
/ 04 апреля 2020

Решите, в какой части прокрутки должна происходить анимация. Затем сопоставьте это с фактическим процентом анимации.

Например, допустим, вы хотите, чтобы анимация происходила в диапазоне от 50% прокрутки до 90% прокрутки. Затем необходимо сопоставить диапазон (0,5-> 0,9) с (0,0-> 1,0).

  • Таким образом, любое входное значение <= 0,5 соответствует выходному значению 0. </li>
  • И любое входное значение> = 0,9 соответствует 1.
  • Значения между ними пропорционально масштабируются между 0 и 1.

См. Функцию mapRange() в следующем примере для кода для этого отображения.

// Get the id of the <path> element and the length of <path>
var triangle = document.getElementById("triangle");
var length = triangle.getTotalLength();

// The start position of the drawing
triangle.style.strokeDasharray = length;

// Hide the triangle by offsetting dash. Remove this line to show the triangle before scroll draw
triangle.style.strokeDashoffset = length;

// Find scroll percentage on scroll (using cross-browser properties), and offset dash same amount as percentage scrolled
window.addEventListener("scroll", myFunction);

function myFunction() {
  var scrollpercent = (document.body.scrollTop + document.documentElement.scrollTop) / (document.documentElement.scrollHeight - document.documentElement.clientHeight);

  var draw = length * mapRange(scrollpercent, 0.5, 0.9, 0, 1);
  
  // Reverse the drawing (when scrolling upwards)
  triangle.style.strokeDashoffset = length - draw;
}

// Maps n from the range (fromStart->fromEnd) to the range (toStart->toEnd).
function mapRange(n, fromStart, fromEnd, toStart, toEnd) {
  const out = toStart + (n - fromStart) * ((toEnd - toStart) / (fromEnd - fromStart));
  // Exclude any values outside to toStart->toEnd range
  return Math.min(toEnd, Math.max(toStart, out));
}
body {
  min-height: 1000px;
}

svg {
  position: fixed;
  width: 300px;
  height: 300px;
}
<h2>Scroll down this window to draw a triangle.</h2>
<p>Scroll back up to reverse the drawing.</p>

<svg id="mySVG">
  <path fill="none" stroke="red" stroke-width="3" id="triangle" d="M150 0 L75 200 L225 200 Z" />
  Sorry, your browser does not support inline SVG.
</svg>
...