[JavaScript30] 🎞 28. Video Speed Controller UI


🎞 28. Video Speed Controller UI


マウスの移動に合わせてビデオの再生速度を調整

イニシャルコード
<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Video Speed Scrubber</title>
    <link rel="stylesheet" href="style_JuneHyung.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"></div>
        </div>
      </div>
</body>
</html>
初期画面

🌏 新知


👉 HTMLMediaElement.playbackRate


メディアの再生速度を設定します.
クイッククローズやスローアクションなどのユーザーコントロールを実装します.
通常の再生速度にA値を乗じて現在の速度を取得します.1.0は通常の速度を示します.
注意:
https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/playbackRate

🌏 プロセス


👉 1.変数の宣言

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

👉 2.高さ調節


heightを%に調整
const speed = document.querySelector('.speed');
const bar = speed.querySelector('.speed-bar');
const video = document.querySelector('.flex');

speed.addEventListener('mousemove', function(e){
    // console.log(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) + '%';
    console.log(height);

    bar.style.height = height;
    // console.log(y);
    // console.log(percent);
});

👉 3.比例調整


メディアの再生速度を計算します.
const speed = document.querySelector('.speed');
const bar = speed.querySelector('.speed-bar');
const video = document.querySelector('.flex');

speed.addEventListener('mousemove', function(e){
    // console.log(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;
    console.log(height);

    bar.style.height = height;
    bar.textContent = playbackRate.toFixed(2) + 'x';
    // console.log(y);
    // console.log(percent);
});

👉 4.ビデオアプリケーションと方法の分離


ビデオのplaybackRate値を計算値に設定します.
video.playbackRate = playbackRate;
メソッド分離.
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);