我正在使用 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/