2

我正在使用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%" }} />
        </>
    )
}

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

4

1 回答 1

4

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

<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 中,所以为什么您不需要网络摄像头本身的宽度和高度,但 videoContrainst 应该具有宽度和高度

于 2020-06-08T00:32:32.020 回答