首页 > 解决方案 > 我想在视频中绘制(使用html5画布)反应

问题描述

我的简单 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>
    );
}

标签: javascriptreactjshtml5-canvashtml5-video

解决方案


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

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

如果是这样,画布和视频将重叠,并且画布将像这样放置在视频的顶部: 在此处输入图像描述

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

谢谢


推荐阅读