I'm using react-web-cam to access the webcam. I want to draw the stream into a canvas because I want to draw a square on top of the stream. I was able to do that using a canvas object. The code is the following and it works:
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%" }} />
</>
)
}
The problem with this is that there are 2 streams being shown right now (from the <Webcam> and <canvas>). How could I stay only with the canvas output? I tried "hiding" the react-web-cam component, but the canvas just outputs a black image. By "hiding" I mean assigning display: 'none' to the styling of <Webcam> component.