iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 28
0
Modern Web

JavaScript 30實作心得筆記系列 第 28

Day28 Video Speed Controller UI

Day28 Video Speed Controller UI

第28天實作目標為做出移動特定元素即可控制影片播放速率,類似於input元素中的滑動桿。

這次是以上下拉動的元素來控制速率。

<div class="speed">
  <div class="speed-bar">1×</div>
</div>

在控制條元素<div class="speed"></div>中建立滑鼠移動mousemove事件,在事件中取得滑鼠在控制條元素中長度的位置const y = e.pageY - this.offsetTop,並取得控制條元素的長度const percent = y / this.offsetHeight,去計算滑鼠在控制條元素的相對位置的百分比const height = Math.round( percent * 100 )+'%',之後百分比轉換成播放速率const playRate = percent * (max - min) + min

function handleMove(e){
    const y = e.pageY - this.offsetTop
    const percent = y / this.offsetHeight
    const max = 4
    const min = 0.4
    const height = Math.round( percent * 100 )+'%'
    const playRate = percent * (max - min) + min

    speedBar.style.height = height
    speedBar.textContent = playRate.toFixed(2) + 'x'
    video.playbackRate = playRate
}

speed.addEventListener('mousemove', handleMove)

之後加入控制條中加入高度speedBar.style.height = height,設定播放速度內容video.playbackRate = playRate,設定顯示速率值speedBar.textContent = playRate.toFixed(2) + 'x'

Html

<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>

Javascript

  1. Number.prototype.toFixed()
    toFixed()固定格式的數值。
function financial(x) {
  return Number.parseFloat(x).toFixed(2);
}
console.log(financial(123.456));
// expected output: "123.46"
console.log(financial(0.004));
// expected output: "0.00"
console.log(financial('1.23e+5'));
// expected output: "123000.00"
tags: MouseEvent

上一篇
Day27 Click and Drag to Scroll
下一篇
Day29 Countdown Clock
系列文
JavaScript 30實作心得筆記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言