На странице есть несколько разделов, и я хочу, чтобы элемент приостановил движение
всякий раз, когда полный раздел виден в Viewport. /> Свяжите позицию элемента вдоль пути к позиции прокрутки. Есть ли библиотека или техника, которая облегчает это? Любые советы или пример кода будут оценены.
Код: Выделить всё
const circle = document.getElementById('circle');
const path = document.getElementById('myPath');
const pathLength = path.getTotalLength();
circle.style.position = 'absolute';
function updateCirclePosition() {
const scrollPercentage = window.scrollY / (document.body.scrollHeight - window.innerHeight);
const pathPoint = path.getPointAtLength(scrollPercentage * pathLength);
circle.style.left = pathPoint.x - 10 + 'px';
circle.style.top = pathPoint.y - 10 + 'px';
}
window.addEventListener('scroll', updateCirclePosition);
updateCirclePosition();< /code>
body {
height: 200vh;
margin: 0;
display: flex;
justify-content: center;
align-items: center;
}
#container {
position: relative;
width: 400px;
height: 200px;
}
#myPath {
fill: none;
stroke: black;
stroke-width: 2;
}
#circle {
position: absolute;
width: 20px;
height: 20px;
border-radius: 50%;
background-color: red;
}< /code>
Scroll-Based SVG Animation
Хотя этот пример работает, есть некоторые проблемы, я не могу остановить SVG в середине экрана, когда я хочу, элемент не находится в середине экрана, в то время как анимация идет
Подробнее здесь: https://stackoverflow.com/questions/796 ... -scrolling
Мобильная версия