Search code examples
javascriptgetusermedia

Turn of webcam after snapshot


I use this code in order to GetUserMedia() and take a snapshot. I would like the camera to turn off after the snap-shot is taken, any tips on how to accomplish this?

$("#btnSaves").click(function () {

    var video = document.querySelector('#webcam');
    var button = document.querySelector('#screenshot-button');
    var canvas = document.querySelector('#screenshot-canvas');
    var ctx = canvas.getContext('2d');

    navigator.getUserMedia = (navigator.getUserMedia ||
                    navigator.webkitGetUserMedia ||
                    navigator.mozGetUserMedia ||
                    navigator.msGetUserMedia);
    if (navigator.getUserMedia) {
        navigator.getUserMedia
                    (
                      { video: true },
                      function (localMediaStream) {
                          video.src = window.URL.createObjectURL(localMediaStream);
                      }, onFailure);
    }
    else {
        onFailure();
    }
    button.addEventListener('click', snapshot, false);

    function snapshot() {
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;
        ctx.drawImage(video, 0, 0);
    }
});

Solution

  • you should save a reference to your stream, like this:

    function (localMediaStream) {
        myStream = localMediaStream;
        video.src = window.URL.createObjectURL(myStream);
    }, onFailure);
    

    later on you can use:

    myStream.stop(); 
    myStream = null;