javascript 如何使用react-webcam只显示视频画布

vddsk6oq  于 2023-04-10  发布在  Java
关注(0)|答案(1)|浏览(108)

我正在使用react-web-cam访问网络摄像头。我想把视频流绘制到画布上,因为我想在视频流上绘制一个正方形。我可以使用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>)。我怎么能只停留在画布输出?我试图“隐藏”react-web-cam组件,但画布只是输出一个黑色的图像。“隐藏”我的意思是将display: 'none'分配给<Webcam>组件的样式。

k97glaaz

k97glaaz1#

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

相关问题