import React , { useRef , useEffect , RefObject } from "react" ; type TImageSnapshot = { data : Uint8ClampedArray ; height : number ; width : number ; } ; export const GreenScreen = ( ) => { const canvasRef = useRef < HTMLCanvasElement > ( null ) ; const videoRef = useRef < HTMLVideoElement > ( null ) ; useEffect ( ( ) => { const canvas = canvasRef . current ?. getContext ( "2d" ) as CanvasRenderingContext2D ; const video = videoRef . current ; const constraints = { audio : false , video : { width : 640 , height : 480 } , } ; function rapidRefresh ( video , canvas ) { canvas . drawImage ( video , 0 , 0 ) ; processImage ( canvas , canvasRef ) ; setTimeout ( ( ) => { rapidRefresh ( video , canvas ) ; } , 0 ) ; } if ( video !== null ) { navigator . mediaDevices . getUserMedia ( constraints ) . then ( ( mediaStream ) => { video . srcObject = mediaStream ; video . onloadeddata = ( ) => { video . play ( ) ; rapidRefresh ( video , canvas ) ; } ; } ) . catch ( ( error ) => { console . error ( { error } ) ; } ) ; } } , [ ] ) ; function processImage ( canvas , canvasRef ) { if ( canvasRef . current === null ) return ; const snapshot = canvas . getImageData ( 0 , 0 , canvasRef . current . width , canvasRef . current . height ) ; const numberOfPixels = snapshot . data . length / 4 ; for ( let i = 0 ; i < numberOfPixels ; i ++ ) { const red = snapshot . data [ i * 4 ] ; const green = snapshot . data [ i * 4 + 1 ] ; const blue = snapshot . data [ i * 4 + 2 ] ; const colorToRemove = green ; if ( colorToRemove > red && colorToRemove > blue && colorToRemove > 100 ) { snapshot . data [ i * 4 + 3 ] = 0 ; } } canvas . putImageData ( snapshot , 0 , 0 ) ; return ; } return ( < div style = { { display : "grid" , gridTemplateColumns : "1fr 1fr" , gridAutoFlow : "column" , gridGap : "1rem" , } } > < div style = { { border : "5px solid #624de3" , width : "max-content" } } > video < br / > < video ref = { videoRef } style = { { transform : "scaleX(-1)" , width : "640px" , height : "480px" , } } > < /video> < /div> < div style = { { border : "5px solid #624de3" , width : "max-content" } } > canvas < br / > < canvas ref = { canvasRef } width = "640" height = "480" style = { { transform : "scaleX(-1)" , } } > < /canvas> < /div> < /div>); } ;