jbialobr / JsQRScanner

JavaScript QR Code scanner for HTML5 supporting browsers
Apache License 2.0
309 stars 115 forks source link

Unable to deactivate the camera stream #23

Open blakemcdermott opened 4 years ago

blakemcdermott commented 4 years ago

My assumptions would be that using .removeFrom( htmlElement ) or .stopScanning() would deactivate the camera stream; however, I'm not having success with this. Does anyone have any suggestions on how to deactivate the camera stream setup when using .appendTo( htmlElement )?

froger-me commented 4 years ago

I think you need to make sure the call to .removeFrom( htmlElement ) is done when .appendTo( htmlElement ) has finished executing, seems to happen async. Calling one right after the other and putting log calls in the browser support cache file like below shows the scanner is undefined. That was my issue.

function $stopWebcam(scanner){
  console.log(scanner);
  if (scanner.videoStream) {
    var stream = scanner.videoStream;
    stream.stop?stream.stop():stream.getTracks && stream.getTracks().forEach(function(track){
      track.stop();
    }
    );
    scanner.videoStream = null;
  }
}
abdulwahidgul24085 commented 4 years ago

This is how I am doing it with Jquery Attached to modal shown and hide

jb_scanner = '';
        //this function will be called when JsQRScanner is ready to use
        $('#qrcode').on('shown.bs.modal', function JsQRScannerReady() {
            //create a new scanner passing to it a callback function that will be invoked when
            //the scanner succesfully scan a QR code
            var jbScanner = new JsQRScanner(onQRCodeScanned);
            //var jbScanner = new JsQRScanner(onQRCodeScanned, provideVideo);
            //reduce the size of analyzed image to increase performance on mobile devices
            jbScanner.setSnapImageMaxSize(300);
            jbScanner.setScanInterval(300);
            var scannerParentElement = document.getElementById("scanner");
            if (scannerParentElement) {
                //append the jbScanner to an existing DOM element
                jbScanner.appendTo(scannerParentElement);
            }
            jb_scanner =  jbScanner;
        });

        $('#qrcode').on('hide.bs.modal', function() {
            if($('.qrPreviewVideo').length){
                $('.qrPreviewVideo').remove();
                var scannerParentElement = document.getElementById("scanner");
                if(scannerParentElement){
                    jb_scanner.removeFrom(scannerParentElement);
                    jb_scanner.stopScanning();
                }
            }
        })