簡體   English   中英

如何使用 react-webcam 僅顯示視頻 canvas

[英]How to only show video canvas using react-webcam

我正在使用react-web-cam來訪問網絡攝像頭。 我想將 stream 繪制到 canvas 中,因為我想在 stream 的頂部繪制一個正方形。 我能夠使用 canvas object 做到這一點。 代碼如下,它可以工作:

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 output? 我嘗試“隱藏” 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"}
            />

如果您為網絡攝像頭本身指定寬度和高度,我認為它基本上會將<video style="width=90% height=90%"> </video>注入到您的 html 中,這樣您就不需要網絡攝像頭本身的寬度和高度,但 videoContrainst 應該具有寬度和高度

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM