javascript - 如何仅使用 react-webcam 显示视频 Canvas

标签 javascript reactjs canvas 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 输出?我尝试“隐藏”react-web-cam 组件,但 Canvas 只输出黑色图像。 “隐藏”是指分配 display: 'none'<Webcam> 的样式组件。

最佳答案

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

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

如果您为网络摄像头本身指定宽度和高度,我认为它的作用基本上是注入(inject) <video style="width=90% height=90%"> </video>到你的 html 中,这样你的网络摄像头本身就不需要宽度和高度,但 videoContrainst 应该有宽度和高度

关于javascript - 如何仅使用 react-webcam 显示视频 Canvas ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62253056/

相关文章:

reactjs - 你应该如何使用 flowtype redux thunk ?

php - 带有 Canvas 的 Bootstrap 复选框

java - 将 MouseListener 与 vlcj 一起使用

javascript - Canvas 圆弧偏移从 1.5PI 开始

javascript - 数组中有值,但无法访问它们,可能是什么问题?

javascript - 右键单击元素显示div

javascript - 为什么 push 显示 argument of type 'any[]' is not assignable to parameter of type 'never' 错误?

javascript - 如何将 css 文件添加到页面正文?

javascript - 是否可以在 Material 表上制作所需的字段

javascript - NextJS Rewrites TypeError : (0 , _resolveRewrites.default) 不是函数