Reputation: 98
I need to draw the stream from camera on top of a canvas using drawImage, however when I add the video element in react component it shows the element's stream in the page too. If I use display:'none' drawImage can't draw the user's webcam, it draws blank screen. Do I have to show html5 video element in the page or is there a way to play it without showing?
I am getting video stream from camera with getUserMedia:
async function getCameraStream() {
try {
const constraint = { video: true }
const stream = await navigator.mediaDevices.getUserMedia(constraint)
if (videoRef.current) {
videoRef.current.srcObject = stream
return
}
} catch (error) {
console.error('Error opening video camera.', error)
}
setLoading(false)
setCameraError(true)
}
And the video ref is:
return( <video
style={{display: 'none' }}
ref={videoRef}
className={classes.sourcePlayback}
src={sourceUrl}
hidden={isLoading}
autoPlay
playsInline
controls={false}
muted
loop
onLoadedData={handleVideoLoad}
/>)
I am using this videoRef in canvas like:
ctx.drawImage(sourcePlayback.htmlElement, 0, 0)
Here if the htmlElement is given with display:'none' it doesn't draw. I want to draw the htmlElement but not show it in the page.Is there a way to achieve this? I want html5VideoElement to play invisibly basically.display:none does not work.
EDIT:
Add css as visibility:'hidden' works for this one.
sourcePlayback: {
visibility: 'hidden',
display: 'flex',
width: 0,
height: 0,
},
Upvotes: 2
Views: 1663
Reputation: 1765
I was able to replicate your issue in chrome with https://record.a.video.
When I used display: none
on the video attribute, the video overlay on the canvas was black instead of my camera.
Workaround:
When I set the CSS on the video to width:1px
, the video shows up on the canvas. I suppose it's technically on the screen, but it'll probably work for your purposes.
Upvotes: 3