개발/JavaScript 30
28. Video Speed Controller
Sangminnn
2017. 4. 27. 00:59
반응형
기본 코드
<!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="https://www.dropbox.com/s/nf6jfkwck1glsyo/12%20-%20flex-wrapping-and-columns.mp4?dl=1" loop controls></video>
<div class="speed">
<div class="speed-bar">1×</div>
</div>
</div>
<script>
</script>
</body>
</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="https://www.dropbox.com/s/nf6jfkwck1glsyo/12%20-%20flex-wrapping-and-columns.mp4?dl=1" loop controls></video>
<div class="speed">
<div class="speed-bar">1×</div>
</div>
</div>
<script>
</script>
</body>
</html>
목표
비디오의 속도를 조절할 수 있는 속도바를 만들어보자.
코드 분석
사용할 변수를 선언한다.
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) + '×';
video.playbackRate = playbackRate;
}
speed.addEventListener('mousemove', handleMove);
사용할 변수를 선언한다.
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) + '×';
video.playbackRate = playbackRate;
}
speed.addEventListener('mousemove', handleMove);
.pageY
는 페이지의 윗부분을 기준으로 마우스가 얼마나 떨어져있는지를 나타내는 값Math.round
는 반올림한다는 메서드이고, toFixed()
는 괄호안의 숫자자리까지 반올림하는 메서드이다.
따라서 정리해보면 y
값을 원하는 위치에서의 y
값, 즉 속도바에서의 높이만을 계산할 수 있도록 하고, percent
로 그 안에서의 퍼센테이지를 정해 놓는다.
그 아래 변수들은 다 필요한 값을 숫자응용으로 정해놓은 것이고bar
의 높이값을 적용, textContent
를 이용하여 bar
에 .toFixed(2)
로 소수점 두번째자리까지 반올림하여 나타낸 값을 속도바에 출력한다는 내용이다. 그리고 그 값에 따라 속도를 조절할 수 있도록 선언한 것이다.
마무리
이번에는 속도바에 속도값도 같이 출력하여 속도를 조절하는 방법이여서 색다른 부분이 있었다.
끝.
반응형