Learn how to access the webcamera with javascript, a no-flash solution

Although in internet there are a lot of examples of how to achieve this, we will offer you a recopilation that covers all the needs of this API (start,pause,stop and snapshot working on android,chrome and firefox).

The following code works in Google Chrome (Android and desktop) and Mozilla Firefox.

<div>
  <video id="video" width="500" height="500" autoplay></video>
  <!-- You can make the canvas visible if you want -->
  <canvas id="canvas" width="500" height="500" style="display:none;"></canvas>
  <input type="button" id="takePhoto" value="Photo !"/>
  <input type="button" id="pauseTransmission" value="pause transmission"/>
  <input type="button" id="resumeTransmission" value="resume transmission"/>
</div>

<script type="text/javascript">
  var _streamCopy = null; // If you want to stop the transmission see how this works in Stop Transmision
  var button = document.getElementById('takePhoto');
  var canvas = document.getElementById('canvas');
  var context = canvas.getContext("2d");
  var video = document.getElementById('video');
  var videoSettings = {
    audio:false,
    video:true
  };
  var onError = function(err){
    console.log(err);
    console.log(err.name);
  };

  // Start the camera when the DOM is ready
  window.addEventListener("DOMContentLoaded",function(){
        if(navigator.getUserMedia) { // Standard
		navigator.getUserMedia(videoObj, function(stream) {
                        _streamCopy = stream;
			video.src = stream;
			video.play();
		}, onError);
	} else { 
	       navigator.mozGetUserMedia(videoObj, function(stream){
                        _streamCopy = stream;
		if (video.mozSrcObject !== undefined) {
  			video.mozSrcObject = stream;
  		} else {
  			video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  		};
  		video.play();
  	      }, onError);
	}
  },false);
  
  // when the button is clicked, draw the video on the canvas, get a base64 image an open it in a new window.
  button.addEventListener('click',function(){
    context.drawImage(video, 0, 0, 500, 500);
    var image = canvas.toDataURL();
    window.open(image);
  },false);

  // Pause transmission on click button 

  document.getElementById('stopTransmission').addEventListener('click',function(){
    video.pause();
  },false);

  document.getElementById('resumeTransmission').addEventListener('click',function(){
    video.play();
  },false);
</script>

Note : Remember you need to run the previous example from a http or https connection, otherwise the getUserMedia API will be not available in file:// protocol.

Handle errors

Those are all the available error code in the getUserMedia API, change the onError event of the previous code for the following :

var onError = function(err){
        switch(err.name){
            case 'PermissionDeniedError':
                alert("Permission to use a media device was denied by the user or the system.");
            break;
            case 'NotFoundError':
                alert('No media tracks of the type specified were found that satisfy the constraints specified.');
            break;
            default:
                alert("An unknown error just happened ! :(");
            break;
        }
};

Stop transmission

If you want to stop the transmission dinamically, we will use the following code :

// _streamCopy is declared in the first example ()

try{
    _streamCopy.stop(); // if this method doesn't exist, the catch will be executed.
}catch(e){
   _streamCopy.getVideoTracks()[0].stop(); // then stop the first video track of the stream
}

Only add a button and a event listener and execute the code. Remember to copy the stream variable whose is generated in the getUserMedia method.

Have fun !


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors