如何使用反应钩子获取网络摄像头提要? [英] How to get webcam feed with react hooks?

查看:50
本文介绍了如何使用反应钩子获取网络摄像头提要?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

参见 如何在 React 中访问 DOM 元素? 而不是 document.querySelector.

当使用 useRef 钩子和修复时useEffect 需要多久执行一次,它看起来像这样:

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

这篇关于如何使用反应钩子获取网络摄像头提要?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆