简体   繁体   中英

ReactJS canvas drawImage without showing html5 video element

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,
    },

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM