0

I am having a problem with getUserMedia.

I have a video tag wich gets the stream, no worries there.

Then i have a canvas in wich i paste the stream into.

For a reason i cannot understand, the image is really big in the canvas, like three times the size ! and it is sort of compressed too but this is not the biggest issue i can fix it later on.

Please note that the canvas size and the video size have the same width and height, but for some reason the ratio is crazy.

Also i have check the webcam resolution and it is 640*480. i sort of fiddled around this at some point but i don't know...

Here is the code in React :

import { useEffect, useRef, useState } from "react"
import './styles/cameraPwa.css'

const CameraPwa = () => {
  const videoRef = useRef()
  const canvasRef = useRef()
  const[videoSpecs, setVideoSpecs] = useState()
  
  useEffect(() => {
    if(videoRef?.current?.srcObject) {
      const tracks = videoRef.current.srcObject.getTracks();
      tracks.forEach(track => track.stop());
    }

    window.navigator.mediaDevices.getUserMedia({
      video: {
      facingMode: "user",
      },
      audio: false
     }).then(stream => {
      if(videoRef.current) {
        videoRef.current.srcObject = stream;
      }
      }).catch((err)=> console.error(err))

    },[])

    function handleCanPlay() {
      setVideoSpecs({width: videoRef.current.offsetWidth, height: videoRef.current.offsetHeight})
      videoRef.current.play();
    }
    
    const handleTakePhoto = () => {
      const ctx = canvasRef.current.getContext('2d')
      ctx?.drawImage(videoRef.current, 0, 0, videoSpecs.width, videoSpecs.height, 0, 0, videoSpecs.width, videoSpecs.height);
    }
   return (
    <div style={{position: 'relative'}}>
      <div>
        <video 
          className="video" 
          onCanPlay={handleCanPlay} 
          ref={videoRef} 
          autoPlay 
          muted 
          playsInline />
      </div>
      <canvas 
        ref={canvasRef} 
        style={{ width: window.innerWidth, height: window.innerHeight}}/>
      <button 
        style={{position: 'absolute',bottom:'1rem', right:'1rem', zIndex:'150'}}
        onClick={handleTakePhoto}>Shoot !
      </button>
    </div>
   )
}

export default CameraPwa
julBayonna
  • 409
  • 7
  • 19
  • 1
    You need to set the `width` and `height` attributes of your canvas to the ones of your video media (`videoRef.current.videoWidth` and `videoRef.current.videoHeight` respectively). – Kaiido Oct 13 '22 at 09:32

0 Answers0