【问题标题】:I want to draw (using html5 canvas) inside video in react我想在视频中绘制(使用 html5 画布)反应
【发布时间】:2021-02-12 13:01:49
【问题描述】:

我的简单 React 应用程序中有两个功能,一个播放视频源的视频标签,以及一个使用 html5 画布制作的钢笔工具。我希望能够使用该钢笔工具在我的视频中绘图。 我一直在谷歌上搜索一个答案,但还没有找到一个明确的方法。

看看我的代码

function App(props) {
    const canvasRef = useRef(null);
    const contextRef = useRef(null);
    const [isDrawing, setIsDrawing] = useState(false);

    useEffect(() => {
        const canvas = canvasRef.current;
        canvas.width = window.innerWidth * 2;
        canvas.height = window.innerHeight * 2;
        canvas.style.width = `${window.innerWidth}px`;
        canvas.style.height = `${window.innerHeight}px`;

        const context = canvas.getContext('2d');
        context.scale(2, 2);
        context.lineCap = 'round';
        context.strokeStyle = 'black';
        context.lineWidth = 5;
        contextRef.current = context;
    }, []);

    const startDrawing = ({ nativeEvent }) => {
        const { offsetX, offsetY } = nativeEvent;
        contextRef.current.beginPath();
        contextRef.current.moveTo(offsetX, offsetY);
        setIsDrawing(true);
    };

    const finishDrawing = () => {
        contextRef.current.closePath();
        setIsDrawing(false);
    };

    const draw = ({ nativeEvent }) => {
        if (!isDrawing) {
            return;
        }
        const { offsetX, offsetY } = nativeEvent;
        contextRef.current.lineTo(offsetX, offsetY);
        contextRef.current.stroke();
    };

    // return <canvas onMouseDown={startDrawing} onMouseUp={finishDrawing} onMouseMove={draw} ref={canvasRef} />;
    return (
   <div>
      <canvas onMouseDown={startDrawing} onMouseUp={finishDrawing} onMouseMove={draw} ref={canvasRef} />
        <video id="v" controls loop width="500">
            <source src={video} type="video/mp4" />
        </video>
   </div>
    );
}

【问题讨论】:

    标签: javascript reactjs html5-canvas html5-video


    【解决方案1】:

    这是可能的。 首先,您需要像这样对画布应用一些样式: position: absolute;z-index: 999;.

    然后您可以将其他样式应用于视频,如下所示: z-index: 11;

    如果是这样,画布和视频将重叠,并且画布将放置在视频顶部,如下所示:

    在这里,您会遇到一个问题...例如,在某些情况下您可能想要控制视频。意思是,您想随时pause/play/stop 视频。 为此,您还需要为视频设置自定义暂停、播放和停止按钮。但是这些按钮的 z-index 应该高于 999,因为画布的 z-index 是 999。

    谢谢

    【讨论】:

      【解决方案2】:

      【讨论】:

        猜你喜欢
        • 2016-02-23
        • 1970-01-01
        • 2011-09-26
        • 2012-08-22
        • 1970-01-01
        • 2020-05-09
        • 2015-01-20
        • 1970-01-01
        • 2013-04-20
        相关资源
        最近更新 更多