React:如何使视频仅在用户滚动时播放,然后移动到其他内容?

问题描述 投票:0回答:1

使用 React,我需要允许用户滚动浏览视频,或通过向后滚动返回。当他们滚动视频时,视频应该完全保持在框架内。当他们到达视频末尾时,应该允许他们向下滚动到页面上的其他内容。 (示例行为,尽管我认为实现是不同的:https://orangecomet.com/

我尝试了几个库,例如 Scrollyvideo,但没有任何效果。例如,React Scrollyvideo 导入不会保持锁定在帧中,而是在播放视频时滚动经过视频。我不知道如何解决这个问题;它的默认位置已经是粘性的。

这是我得到的一个半工作的东西,试图将this转换为React,但它一点也不好,因为它不允许任何东西出现在它下面:

import React, { useEffect, useRef, useState } from "react";

const ScrollVideo = () => {
  const videoRef = useRef(null);
  const playbackConst = 500;
  const videoLength = 10;
  const videoHeight = `${videoLength * playbackConst}px`;

  useEffect(() => {
    const vid = videoRef.current;

    const scrollPlay = () => {
      const frameNumber = window.scrollY / playbackConst;
      vid.currentTime = frameNumber;

      window.requestAnimationFrame(scrollPlay);
    };

    window.requestAnimationFrame(scrollPlay);
  }, []);

  return (
    <>
      <div id="set-height" style={{ height: videoHeight }}>
        <video
          id="v0"
          tabIndex={0}
          // autoBuffer="autobuffer"
          preload="preload"
          ref={videoRef}
          style={{
            position: "fixed",
            top: 0, 
            left: 0,
            width: "100%",
          }}
        >
          <source
            type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"'
            src="/neural.mp4"
          ></source>
        </video>
      </div>
    </>
  );
};

export default ScrollVideo;

这实际上达到了我想要的效果,只是我需要将其更改为仅在视频顶部位于帧中时才启动行为;但它依赖于滚动条劫持,这显然接近禁忌:

import React, { useState, useRef, useEffect } from "react";
import ReactPlayer from "react-player";

const ScrollVideo = () => {
  const [duration, setDuration] = useState(0);
  const playerRef = useRef(null);

  const handleScroll = (e) => {
    if (playerRef.current && duration) {
      const currentTime = playerRef.current.getCurrentTime();
      let newTime = currentTime + e.deltaY * 0.02;

      if (newTime <= 0) {
        playerRef.current.seekTo(0, "seconds");
      } else if (newTime >= duration) {
        playerRef.current.seekTo(duration, "seconds");
      } else {
        e.preventDefault();
        playerRef.current.seekTo(newTime, "seconds");
      }
    }
  };

  useEffect(() => {
    window.addEventListener("wheel", handleScroll, { passive: false });

    return () => {
      window.removeEventListener("wheel", handleScroll);
    };
  }, [duration]);

  return (
    <div style={{ width: "100%", height: "100vh", overflow: "hidden" }}>
      <ReactPlayer
        ref={playerRef}
        url="neural.mp4"
        width="80%"
        height="80%"
        onDuration={setDuration}
      />
    </div>
  );
};

export default ScrollVideo;
reactjs video scroll
1个回答
0
投票

我也遇到这个问题了。目前正在使用 Scrolly,但它并不能真正完成我希望它工作的事情。

© www.soinside.com 2019 - 2024. All rights reserved.