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

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

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

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%" }} />
        </>
    )
}

问题在于,现在显示了两个流(来自<Webcam><canvas>)。我怎么能只保留画布输出?我尝试“隐藏” react-web-cam组件,但是画布仅输出黑色图像。 “隐藏”是指将display: 'none'分配给<Webcam>组件的样式。

javascript reactjs canvas webcam
1个回答
0
投票

ctx.drawImage(video.video, 0, 0, canvas.width, canvas.height);部分之后将视频widthheight分配给0%

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