cha*_*lie 5 javascript webcam canvas reactjs
我正在使用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%" }} />
</>
)
}
Run Code Online (Sandbox Code Playgroud)
问题是现在显示 2 个流(来自 和<Webcam>)<canvas>。我怎么能只保留画布输出呢?我尝试“隐藏”react-web-cam 组件,但画布只输出黑色图像。我所说的“隐藏”是指分配display: 'none'给组件的样式<Webcam>。
<Webcam
audio={true}
ref={webcamRef}
mirrored
style={{
width: "0%",
height: "0%",
}}
videoConstraints={{
width: 1280,
height: 720,
facingMode: "user",
}}
/>
Run Code Online (Sandbox Code Playgroud)