如何使用 React Hooks 获取网络摄像头?

How to get webcam feed with react hooks?

我正在尝试使用 React Hooks 获取网络摄像头源以显示在我的应用程序上。我还需要能够从提要中捕获最新图像

我相信我有基础,但还缺少一些东西。

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

找到问题。

改变

 video.source = stream;

收件人:

 video.srcObject = stream;

中提琴

请参阅 而不是 document.querySelector

当应用 useRef 钩子并修复 useEffect 需要执行的频率时,它看起来像这样:

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