Created
November 11, 2021 20:40
-
-
Save lejonmanen/f44e5047c146e2dc88a320ac1dd120f3 to your computer and use it in GitHub Desktop.
Use MediaDevices to display video stream from webcam in a React component.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useRef } from 'react' | |
const MediaDevice = () => { | |
const videoRef = useRef(null) | |
const handleVideoOn = () => assignStream(videoRef.current) | |
const handleVideoOff = () => videoRef.current.srcObject = null | |
return ( | |
<div> | |
<p> | |
<button onClick={handleVideoOn}> Turn video on </button> | |
<button onClick={handleVideoOff}> Turn video off </button> | |
</p> | |
<video ref={videoRef}> </video> | |
</div> | |
) | |
} | |
async function assignStream(videoElement, constraints = { video: true }) { | |
const stream = await navigator.mediaDevices.getUserMedia(constraints) | |
videoElement.srcObject = stream | |
videoElement.addEventListener('loadedmetadata', () => { | |
videoElement.play() | |
}) | |
} | |
export default MediaDevice |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment