iT邦幫忙

2024 iThome 鐵人賽

DAY 6
0

Day28 要來做個影片速度的控制器

資料

const VIDEO_URL =
  "https://github.com/wesbos/JavaScript30/raw/master/11%20-%20Custom%20Video%20Player/652333414.mp4";
  const [playbackRate, setPlaybackRate] = useState<number>(1);
  const videoRef = useRef<HTMLVideoElement>(null);
  const speedBarRef = useRef<HTMLDivElement>(null);

動作

  const handleSpeedChange = (e: MouseEvent<HTMLDivElement>) => {
    const speedBar = speedBarRef.current;
    const video = videoRef.current;
    if (!speedBar || !video) {
      return;
    }

    const y = e.nativeEvent.offsetY;
    const percent = y / speedBar.offsetHeight;
    const min = 0.4;
    const max = 4;
    const newPlaybackRate = percent * (max - min) + min;

    setPlaybackRate(newPlaybackRate);
    video.playbackRate = newPlaybackRate;
  };

畫面結構

  return (
    <div className="flex items-center justify-center h-screen bg-gray-100">
      <div className="relative">
        <video
          className="rounded-lg shadow-lg"
          width="765"
          height="430"
          src={VIDEO_URL}
          ref={videoRef}
          controls
        ></video>
        <div
          className="absolute top-0 right-0 h-full w-10 bg-gray-200 cursor-pointer"
          ref={speedBarRef}
          onClick={handleSpeedChange}
        >
          <div
            className="relative h-full w-full bg-yellow-400 flex items-center justify-center"
            style={{ height: `${((playbackRate - 0.4) / 3.6) * 100}%` }}
          >
            <span className="speed-bar text-xs font-bold text-gray-800">
              {playbackRate.toFixed(2)}x
            </span>
          </div>
        </div>
      </div>
    </div>
  );

DEMO

https://codesandbox.io/p/devbox/kcqgs7


上一篇
[Day27]_Click-and-Drag
下一篇
[Day29]_Countdown-Timer
系列文
React30——用 React 探索 JavaScript30 的魅力30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言