Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to take photo from webcam using HTML5 and getUserMedia() in Google Chrome on first page load

Taking reference from this article on HTML5Rocks I am trying to build a utility to take photo from webcam.

Below is my HTML code snippet:

<button type="button" name="btnCapture" id="btnCapture">Start my camera</button><br />
<video autoplay="true" id="video" style="height:240px;width:320px"></video><canvas id="canvas" style="display: none; height:240px;width:320px"></canvas><br />
<img id="capturedImage" src="/blank.gif" style="height:240px;width:320px"><input type="hidden" id="hdnImageBase64" name="hdnImageBase64"><br />

On click of button btnCapture I start my webcam and clicking it again It captures the photo from webcam and puts it into the image capturedImage.

Below is my JavaScript code:

var video = document.getElementById("video");
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var localMediaStream = null;
var capturedImage = document.getElementById("capturedImage");
var buttonTextCapturePicture = "Say Cheese!";

function onFailSoHard(e) {
    if (e.code == 1) {
        alert("Something went wrong! Either your webcam is not connected or you denied access to it.");
    } else {
        alert("getUserMedia() not supported in your browser. Try using latest version of Google Chrome or Opera.");
    }
}

function snapshot() {
    if (localMediaStream) {
        try {
            ctx.drawImage(video, 0, 0);
            capturedImage.src = canvas.toDataURL("image/png");
            document.getElementById("hdnImageBase64").value = canvas.toDataURL("image/png");
        } catch (e) {
            alert("Something went wrong while capturing you. Try refreshing the page. " + e);
        }
    }
}

video.addEventListener("click", snapshot, false);

function sizeCanvas() {
    setTimeout( function() {
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;
        capturedImage.height = video.videoHeight;
        capturedImage.width = video.videoWidth;
    }, 50);
}

var button = document.getElementById("btnCapture");
button.addEventListener("click", function(e) {
    if (localMediaStream) {
        snapshot();
        return;
    }
    if (navigator.getUserMedia) {
        navigator.getUserMedia("video", function(stream) {
            video.src = stream;
            localMediaStream = stream;
            sizeCanvas();
            button.textContent = buttonTextCapturePicture;
        }, onFailSoHard);
    } else if (navigator.webkitGetUserMedia) {
        navigator.webkitGetUserMedia({"video" : true}, function(stream) {
            video.src = window.webkitURL.createObjectURL(stream);
            localMediaStream = stream;
            sizeCanvas();
            button.textContent = buttonTextCapturePicture;
        }, onFailSoHard);
    } else {
        onFailSoHard({
            target : video
        });
    }
}, false);

When the button btnCapture is clickd first time it calls the function sizeCanvas() to set the canvas and image width & height to video's width & height (i.e. 320 & 240). When the button is clicked second time it take Base64 encoded snapshot from webcam using canvas.toDataURL and puts it into image capturedImage.

It works in Opera. But in Google Chrome it always fails the first time when page is loaded. But when the same page is refreshed it works. Trying to debug I found that the code canvas.toDataURL returns image Base64 as data:, for the first time due to which it is unable to draw image whih results in error of Resource interpreted as Image but transferred with MIME type text/plain: "data:,". in console. Also if I do not call the function sizeCanvas then it works first time but then the picture is not of the dimension I require and gets cropped.

Any ideas how I can make it work in Chrome the first time with sizeCanvas?

Google Chrome: 24.0.1312.57 Opera: 12.11

like image 890
Naveen Avatar asked Feb 14 '13 05:02

Naveen


People also ask

What html5 tag is used to show the contents of a webcam?

To integrate webcam with webpage we will use HTML <video> tag.


1 Answers

LIVE DEMO

Works well in Chrome and FF.

(function() {

  var streaming = false,
      video        = document.querySelector('#video'),
      canvas       = document.querySelector('#canvas'),
      photo        = document.querySelector('#photo'),
      startbutton  = document.querySelector('#startbutton'),
      width = 320,
      height = 0;

  navigator.getMedia = ( navigator.getUserMedia ||
                         navigator.webkitGetUserMedia ||
                         navigator.mozGetUserMedia ||
                         navigator.msGetUserMedia);

  navigator.getMedia(
    {
      video: true,
      audio: false
    },
    function(stream) {
      if (navigator.mozGetUserMedia) {
        video.mozSrcObject = stream;
      } else {
        var vendorURL = window.URL || window.webkitURL;
        video.src = vendorURL.createObjectURL(stream);
      }
      video.play();
    },
    function(err) {
      console.log("An error occured! " + err);
    }
  );

This code I found here: LINK DEVELOPER MOZILLA

UPDATE: I updated my Live Demo to JSFiddle because getUserMedia() is no longer works on insecure origins. To use this feature, you should consider switching your application to a secure origin, such as HTTPS. See The Chromium Projects for more details.

like image 198
Black Sheep Avatar answered Sep 24 '22 13:09

Black Sheep