WEBCAM without Flash

Asked

Viewed 232 times

0

Guys... I’m trying to take a photo with a webcam... I’m relatively new in Javascript and I’m taking a choir!

Follows my code:

   //função para iniciar a camera
   function startCamera(){
      navigator.mediaDevices.getUserMedia({
	  video:{facingMode:'environment'},
	  audio:true
      })
      .then((stream) => {
         document.getElementById('video').srcObject=stream
      })
   }
   //função para parar a camera
   function stopCamera(){
      document.getElementById('video')
      .srcObject
      .getVideoTracks()
      .forEach(track => track.stop())
   }
   //ligar a camer automaticamente
   window.addEventListener("DOMContentLoaded", startCamera())
   //função para tirar foto
		  
   document.querySelector('#btnStart').addEventListener('click', event => {
      const canvas = document.getElementById('pic')
      const context = canvas.getContext('2d')
      const video = document.getElementById('video')
      //tamanho da foto mesmo tamanho do video
      canvas.width = video.offsetWidth
      canvas.height = video.offsetHeight
      //desenha o video no canvas
      context.drawImage(video, 0, 0, canvas.witdh, canvas.height)
      //metodo do canvas para pegar um objeto Blob
      canvas.toBlob(function(blob){
         const url = URL.createObjectURL(blob)
         stopCamera()
      }, 'image/jpeg', 0.95)
      //closeCamera()
   })
   <video src="" id="video" muted autoplay></video>
   <canvas id="pic"></canvas>
		
   <input type="button" id="btnStart" value="Tirar Foto">

So far I could only turn on the camera and show 'LIVE'... I could not make the photo appear on the canvas... it is all black when I click on the button to take the photo.

  • I reversed the issue dear @reculos, because if it does not misread the answer, I am checking the problem and I already add a possible resolution ;)

1 answer

1


Your only mistake is calling the function when declaring:

   window.addEventListener("DOMContentLoaded", startCamera())

The right is the right DOMContentLoaded call, getting like this:

   window.addEventListener("DOMContentLoaded", startCamera)

The other mistake is that the property srcObject is no longer supported since November 2017, then you should use something like (for backward compatibility):

try {
  video.srcObject = mediaSource;
} catch (error) {
  video.src = URL.createObjectURL(mediaSource);
}

There’s a simple typo too, you wrote witdh:

 context.drawImage(video, 0, 0, canvas.witdh, canvas.height)

But the right thing is width:

 context.drawImage(video, 0, 0, canvas.width, canvas.height)

Note: I moved all events inside DOMContentLoaded, both the startCamera as for the click of the button.

Example:

   var tmpStream;

   function setMedia(video, s) {
      tmpStream = s;

      try {
        video.srcObject = s;
      } catch (error) {
        video.src = URL.createObjectURL(s);
      }
   }

   //função para iniciar a camera
   function startCamera(){
      navigator.mediaDevices.getUserMedia({
	  video:{facingMode:'environment'},
	  audio:true
      })
      .then((stream) => {
         setMedia(document.getElementById('video'), stream)
      })
   }
   //função para parar a camera
   function stopCamera(){
      //Se não tiver stream definido ainda
      if (!tmpStream) return;

      tmpStream.getVideoTracks().forEach(track => track.stop())
   }


   //inicia os eventos
   window.addEventListener("DOMContentLoaded", startAll)

   function startAll()
   {
     //ligar a camera automaticamente
     startCamera()

     //função para tirar foto
     document.querySelector('#btnStart').addEventListener('click', event => {
        const canvas = document.getElementById('pic')
        const context = canvas.getContext('2d')
        const video = document.getElementById('video')
        //tamanho da foto mesmo tamanho do video
        canvas.width = video.offsetWidth
        canvas.height = video.offsetHeight
        //desenha o video no canvas
        context.drawImage(video, 0, 0, canvas.width, canvas.height)
        //metodo do canvas para pegar um objeto Blob
        canvas.toBlob(function(blob){
           const url = URL.createObjectURL(blob)
           stopCamera()
        }, 'image/jpeg', 0.95)
        //closeCamera()
     })
   }
   <video src="" id="video" muted autoplay></video>
   <canvas id="pic"></canvas>
		
   <input type="button" id="btnStart" value="Tirar Foto">

  • made the changes... understood the code... would be the same as Document.getElementById('video')=stream with correct error handling? however, it continues with the same error... the camera turns on... the stream appears on the screen, when you click the button to take the photo, the canvas becomes a whole black square! I don’t know if I’m right, but the problem is inside the evendo 'click'... I’ll put the new code above! thanks!

  • Caro @reculos document.getElementById('video')=stream seems incorrect, so I created the function, just for the record, cameras I think only run under HTTPS, but I believe that in localhost should also run, only in FILE:/// maybe does not work, depending on the browser, I’ll test right here and fix any possible error and send you the corrected code

  • Thanks a lot for the help @Guilherme Nascimento, I tried to put in localhost and here but also happened the same thing, after clicking the button, turned a black square instead of canvas, however the stream appears on the screen...

  • in firefox ran... but I needed it to run on Chrome same!

  • @fixed recoils, it was a simple typing error, typed canvas.witdh, but the right thing was canvas.width, enjoy and move everything to a single function to be loaded only when the camera starts in Domcontentloaded ;)

  • Good @Guilherme Nascimento... Thanks... worked perfectly!!!! which IDE would be nice to use to avoid this type of typo?

  • @recoils I do not use any IDE, it is more practical even, if leaving something semi-ready there just to use already help, I like very English, so learn to use the properties and methods of the Apis and even write width is part of this, Personally I think having English writing at least is useful in programming :)

  • yes agree... I asked because it was a typo and not English itself! an IDE that completes the reserved programming words helps avoid typos! anyway, I appreciate the help... I will try to stay more attentive! rss

  • @but I find it interesting this too, learn what are the words "reserved", after all master the language and a little English should be the basic to climb the improvement ladder as a programmer :) ... but it is my people opinion, even if I were of the opinion to indicate a reading: https://codingcraft.com.br/2016/06/01/nao-gost-do-idioma-ingles-saia-da-programacao-isto-nao-e-para-voce/

  • I don’t think you understand me... my English is fluent... and I also know the reserved words... my finger that hit the wrong order of the letters kkk

Show 5 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.