Experience/[Javascript] JS 30

[Javascript] 28. Video Speed Controller

winCow 2021. 5. 12. 13:58

1. 개요

마우스 이동으로 비디오 속도를 조절하는 기능이다.

 

 

2. HTML

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Video Speed Scrubber</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>

  <div class="wrapper">
    <video class="flex" width="765" height="430" src="http://clips.vorwaerts-gmbh.de/VfE_html5.mp4" loop controls></video>
    <div class="speed">
      <div class="speed-bar">1×</div>
    </div>
  </div>

</body>
</html>

 

 

3. CSS

body {
  margin: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: #4C4C4C url('https://unsplash.it/1500/900?image=1021');
  background-size: cover;
  font-family: sans-serif;
}

.wrapper {
  width: 850px;
  display: flex;
}

video {
  box-shadow: 0 0 1px 3px rgba(0,0,0,0.1);
}

.speed {
  background: #efefef;
  flex: 1;
  display: flex;
  align-items: flex-start;
  margin: 10px;
  border-radius: 50px;
  box-shadow: 0 0 1px 3px rgba(0,0,0,0.1);
  overflow: hidden;
}

.speed-bar {
  width: 100%;
  background: linear-gradient(-170deg, #2376ae 0%, #c16ecf 100%);
  text-shadow: 1px 1px 0 rgba(0,0,0,0.2);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 2px;
  color: white;
  height: 16.3%;
}

 

 

4. Javascript

  const speed = document.querySelector('.speed');
  const bar = speed.querySelector('.speed-bar');
  const video = document.querySelector('.flex');

  function handleMove(e) {
    const y = e.pageY - this.offsetTop;
    const percent = y / this.offsetHeight;
    const min = 0.4;
    const max = 4;
    const height = Math.round(percent * 100) + '%';
    const playbackRate = percent * (max-min) + min;
    bar.style.height = height;
    bar.textContent = playbackRate.toFixed(2) + 'x';
    video.playbackRate = playbackRate;
  }

  speed.addEventListener('mousemove', handleMove);

스피드 바가 담긴 div 태그를 speed, 그 안의 스피드 바를 bar, 비디오 태그를 video 변수에 할당한다.

speed에 mousemove에 반응해 handleMove를 실행시키는 이벤트 리스너를 건다.

handleMove는 구체적으로 다음과 같이 정의한다. 전달된 이벤트인 e, 즉 mousemove 이벤트에 대해, 전달된 시점에서의 y좌표인 pageY에서, 스피드 바가 담긴 div 태그인 speed의 offsetTop을 뺀 값을 구하면, 스피드 바가 채워질 거리가 나온다. percent는 이렇게 정의한 y값을 div태그의 offsetHeight, 즉 스피드 바의 전체 길이로 나눠 준 값이므로, y값을 비율로 나타낸 값이 된다. height는 이 percent에 100을 곱한 뒤 반올림을 한 것이고, 이를 bar의 style.height에 적용시키면, 마우스의 움직임에 따라 bar가 채워지는 효과를 가지게 된다.

playbackRate는 위에서 정의한 percent로 비디오의 playbackRate의 최대값과 최소값을 설정한 것이다. 이렇게 만든 playbackRate를 video에 적용하고, bar의 textContent에도 tofixed(2)로 소수점 2번째 자리까지 보이도록 한다. toFixted(n)은 숫자를 고정 소수점 n번째 자리까지 나타내는 함수이다.