如何使用 react-webcam 只显示视频 canvas

How to only show video canvas using react-webcam

我正在使用 react-web-cam 访问网络摄像头。我想将流绘制成 canvas 因为我想在流的顶部绘制一个正方形。我能够使用 canvas 对象来做到这一点。代码如下并且有效:

import Webcam from "react-webcam";
import React, { useRef } from 'react';

const MyComponent = props => {
    const webcamRef = useRef(null);
    const canvasRef = useRef(null);
    function drawImge() {
        const video = webcamRef.current;
        const canvas = canvasRef.current;
        if (video && canvas) {
            var ctx = canvas.getContext('2d');

            canvas.width = video.video.videoWidth;
            canvas.height = video.video.videoHeight;

            // We want also the canvas to display de image mirrored
            ctx.translate(canvas.width, 0);
            ctx.scale(-1, 1);
            ctx.drawImage(video.video, 0, 0, canvas.width, canvas.height);
            ctx.scale(-1, 1);
            ctx.translate(-canvas.width, 0);
            var faceArea = 300;
            var pX = canvas.width / 2 - faceArea / 2;
            var pY = canvas.height / 2 - faceArea / 2;

            ctx.rect(pX, pY, faceArea, faceArea);
            ctx.lineWidth = "6";
            ctx.strokeStyle = "red";
            ctx.stroke();
            setTimeout(drawImge, 33);
        }
    }
    setTimeout(drawImge, 33);
    return (
        <>
            <Webcam
                audio={true}
                ref={webcamRef}
                mirrored
                style={{
                    width: "90%", height: "90%"
                }}
            />
            <canvas ref={canvasRef} style={{ width: "90%", height: "90%" }} />
        </>
    )
}

问题是现在显示了 2 个流(来自 <Webcam><canvas>)。我怎么能只保留 canvas 输出?我尝试 "hiding" react-web-cam 组件,但 canvas 只输出黑色图像。 "hiding" 我的意思是将 display: 'none' 分配给 <Webcam> 组件的样式。

网络摄像头部分 应该是这样的

<Webcam
                audio={true}
                ref={webcamRef}
                mirrored
                style={{
                    width: "0%", height: "0%"
                }}
               videoConstraints={ width: 1280,
  height: 720,
  facingMode: "user"}
            />

如果您为网络摄像头本身指定宽度和高度,我认为它的作用基本上是将 <video style="width=90% height=90%"> </video> 注入您的 html,因此您不需要在您的 html 中设置宽度和高度网络摄像头本身,但 videoContrainst 应该有宽度和高度