<aside> ✋

“페이지를 스크롤하면, 그에 맞춰 영상이 같이 움직이게 해 주세요.“

</aside>

최근에 스크롤에 따라 영상 타임라인이 동기화되는 인터랙션 구현 요청이 있었다. 이번 문서에서는 페이 지를 스크롤할 때마다 영상의 재생 위치를 동기화하는 스크롤 기반 비디오 컨트롤에 대해 소개한다.

📌주요 변수

let isVideoLoaded = false;
const scrollToTimeRatio = 350;
const videoElement = document.querySelector('#video_container .video');
const videoContainer = document.getElementById('video_container');

let lastScrollTime = 0;
const throttleDelay = 100;

🎬 영상 재생 위치 업데이트 함수

const play = () => {
  const scrollPosition = Math.max(0, window.scrollY - videoContainer.offsetTop);
  videoElement.currentTime = scrollPosition / scrollToTimeRatio;
};

⏲️ 스크롤 이벤트 최적화 (Throttle + rAF)

const throttleScroll = () => {
  const currentTime = performance.now();

  if (currentTime - lastScrollTime >= throttleDelay) {
    lastScrollTime = currentTime;
    window.requestAnimationFrame(play);
  }
};