How to get webcam feed with react hooks?

不想你离开。 提交于 2020-07-19 04:50:29

问题


I am trying to get a webcam feed to display on my app using react hooks. I also need to be able to capture the latest image from the feed

I believe I have the foundations but am missing something.

import React,{useState,useEffect} from "react"


export function VideoFeed(){
const[constraints] = useState({width:300,height:300})

useEffect(()=>{
    navigator.mediaDevices.getUserMedia({video:true})
    .then(stream=>{
        let video = document.querySelector('video')
        video.source = stream;
        video.play();
    })
    .catch(e=>{
        console.log(e)
    })
})

return(
    <video autoPlay ={true} id ="video"></video>
)
}

回答1:


See How to access a DOM element in React? instead of document.querySelector.

When applied with useRef hook and fixing how often useEffect needs to execute, it would look something like this:

export function VideoFeed() {
  const videoEl = useRef(null)

  useEffect(() => {
    if (!videoEl) {
      return
    }
    navigator.mediaDevices.getUserMedia({video:true})
      .then(stream => {
        let video = videoEl.current
        video.srcObject = stream
        video.play()
      })
  }, [videoEl])

  return <video ref={videoEl} />
}



回答2:


Found the issue.

Change

 video.source = stream;

To:

 video.srcObject = stream;

Viola



来源:https://stackoverflow.com/questions/55655846/how-to-get-webcam-feed-with-react-hooks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!