Create Qr Code reader with Webcodecam

Asked

Viewed 1,135 times

0

I’m using Webcodecam to detect and scan the value of a barcode or QR code displayed in front of the webcam. A callback function is invoked when the image is Barcode or the QR code is decoded. You can also control the captured zoom level, image brightness, contrast, sharpness, limit, etc.

$('#qr-canvas').WebCodeCam({
    ReadQRCode: true, // false or true
    ReadBarcode: true, // false or true
    width: 320,
    height: 240,
    videoSource: {
      id: true,      //default Videosource
      maxWidth: 640, //max Videosource resolution width
      maxHeight: 480 //max Videosource resolution height
    },
    flipVertical: false,  // false or true
    flipHorizontal: false,  // false or true
    zoom: -1, // if zoom = -1, auto zoom for optimal resolution else int
    beep: "/wordpress/wp-content/themes/better-health/webcodecamjs-master/audio/beep.mp3", // string, audio file location
    autoBrightnessValue: false, // functional when value autoBrightnessValue is int
    brightness: 0, // int 
    grayScale: false, // false or true
    contrast: 0, // int 
    threshold: 0, // int 
    sharpness: [], //or matrix, example for sharpness ->  [0, -1, 0, -1, 5, -1, 0, -1, 0]
    resultFunction: function (resText, lastImageSrc) {
      alert(resText);

    },
    getUserMediaError: function () {
      alert('Sorry, the browser you are using doesn\'t support getUserMedia');
    },
    cameraError: function (error) {
      /* callback funtion to cameraError, 
      example:
      var p, message = 'Error detected with the following parameters:\n';
      for (p in error) {
              message += p + ': ' + error[p] + '\n';
      }
      alert(message);
      */
    }
  });

  $('#qr-canvas').WebCodeCam();
.scanner-laser{
            position: absolute;
            margin: 40px;
            height: 30px;
            width: 30px;
        }
        .laser-leftTop{
            top: 0;
            left: 0;
            border-top: solid red 5px;
            border-left: solid red 5px;
        }
        .laser-leftBottom{
            bottom: 0;
            left: 0;
            border-bottom: solid red 5px;
            border-left: solid red 5px;
        }
        .laser-rightTop{
            top: 0;
            right: 0;
            border-top: solid red 5px;
            border-right: solid red 5px;
        }
        .laser-rightBottom{
            bottom: 0;
            right: 0;
            border-bottom: solid red 5px;
            border-right: solid red 5px;
        }
 <script src="/wordpress/wp-content/themes/better-health/webcodecamjs-master/js/jquery.js"></script>
<script src="/wordpress/wp-content/themes/better-health/webcodecamjs-master/js/webcodecamjs.js"></script>
<script src="/wordpress/wp-content/themes/better-health/webcodecamjs-master/js/webcodecamjquery.js"></script>
<script src="/wordpress/wp-content/themes/better-health/webcodecamjs-master/js/qrcodelib.js"></script>
<script src="/wordpress/wp-content/themes/better-health/webcodecamjs-master/js/DecoderWorker.js"></script>

<body>
    <div style="position: relative;display: inline-block;">
      <canvas id="qr-canvas" width="320" height="240"></canvas>       
      <div class="scanner-laser laser-rightBottom" style="opacity: 0.5;"></div>
      <div class="scanner-laser laser-rightTop" style="opacity: 0.5;"></div>
      <div class="scanner-laser laser-leftBottom" style="opacity: 0.5;"></div>
      <div class="scanner-laser laser-leftTop" style="opacity: 0.5;"></div>
    </div>
  </body>

But when I run the page, I get the following error in the console:

Uncaught Typeerror: $(...). Webcodecam is not a Function at teste1:57

Editing:

I adjusted my code to the recent version but it still doesn’t work:

var txt = "innerText" in HTMLElement.prototype ? "innerText" : "textContent";
            var arg = {
                resultFunction: function(result) {
                    /*
                        result.format: code format,
                        result.code: decoded string,
                        result.imgData: decoded image data
                    */
                    var aChild = document.createElement('li');
                    aChild[txt] = result.format + ': ' + result.code;
                    document.querySelector('body').appendChild(aChild);
                }
            };
    /* -------------------------------------- Available parameters --------------------------------------*/
    var options = {
        DecodeQRCodeRate: 5,                    // null to disable OR int > 0 !
        DecodeBarCodeRate: 5,                   // null to disable OR int > 0 !
        successTimeout: 500,                    // delay time when decoding is succeed
        codeRepetition: true,                   // accept code repetition true or false
        tryVertical: true,                      // try decoding vertically positioned barcode true or false
        frameRate: 15,                          // 1 - 25
        width: 320,                             // canvas width
        height: 240,                            // canvas height
        constraints: {                          // default constraints
            video: {
                mandatory: {
                    maxWidth: 1280,
                    maxHeight: 720
                },
                optional: [{
                    sourceId: true
                }]
            },
            audio: false
        },
        flipVertical: false,                    // boolean
        flipHorizontal: false,                  // boolean
        zoom: -1,                               // if zoom = -1, auto zoom for optimal resolution else int
        beep: '/wordpress/wp-content/themes/better-health/webcodecamjs-master/audio/beep.mp3',                 // string, audio file location
        decoderWorker: '/wordpress/wp-content/themes/better-health/webcodecamjs-masterjs/DecoderWorker.js',   // string, DecoderWorker file location
        brightness: 0,                          // int
        autoBrightnessValue: false,             // functional when value autoBrightnessValue is int
        grayScale: false,                       // boolean
        contrast: 0,                            // int
        threshold: 0,                           // int 
        sharpness: [],      // to On declare matrix, example for sharpness ->  [0, -1, 0, -1, 5, -1, 0, -1, 0]
        resultFunction: function(result) {
            /*
                result.format: code format,
                result.code: decoded string,
                result.imgData: decoded image data
            */
            alert(result.code);
        },
        cameraSuccess: function(stream) {           //callback funtion to camera success
            console.log('cameraSuccess');
        },
        canPlayFunction: function() {               //callback funtion to can play
            console.log('canPlayFunction');
        },
        getDevicesError: function(error) {          //callback funtion to get Devices error
            console.log(error);
        },
        getUserMediaError: function(error) {        //callback funtion to get usermedia error
            console.log(error);
        },
        cameraError: function(error) {              //callback funtion to camera error  
            console.log(error);
        }
    };

    /*---------------------------- Example initializations Javascript version ----------------------------*/
    new WebCodeCamJS("canvas").init(arg);
    /* OR */
    var canvas = document.querySelector('#webcodecam-canvas');
    new WebCodeCamJS(canvas).init();
    /* OR */
    new WebCodeCamJS('#webcodecam-canvas').init();

    /*------------------------ Example initializations jquery & Javascript version ------------------------*/
    var decoder = new WebCodeCamJS('#webcodecam-canvas');

    var decoder = $("#webcodecam-canvas").WebCodeCamJQuery(args).data().plugin_WebCodeCamJQuery;

    decoder.buildSelectMenu('#camera-select', sel); //sel : default camera optional
    /* Chrome & MS Edge: build select menu
    *  Firefox: the default camera initializes, return decoder object 
    */
    //simple initialization
    decoder.init();
    /* Select environment camera if available */
    decoder.buildSelectMenu('#camera-select', 'environment|back').init(args);
    /* Select user camera if available */
    decoder.buildSelectMenu('#camera-select', 'user|front').init(args);
    /* Select camera by name */
    decoder.buildSelectMenu('#camera-select', 'facecam').init(args);
    /* Select first camera */
    decoder.buildSelectMenu('#camera-select', 0).init(args);
    /* Select environment camera if available, without visible select menu*/
    decoder.buildSelectMenu(document.createElement('select'), 'environment|back').init().play();   

    /* --------------------------------------- Available Functions: ----------------------------------------*/
    /* camera stop & delete stream */
    decoder.stop();
    /* camera play, restore process */
    decoder.play();
    /* get current image from camera */
    decoder.getLastImageSrc();
    /* decode local image */
    /* if url is defined download image before staring open process */
    decoder.decodeLocalImage(url);
    /* get optimal zoom */
    decoder.getOptimalZoom();
    /* Configurable options */
    decoder.options['parameter'];
    /* Example: 
    ** decoder.options.brightness = 20;         - set brightness to 20
    ** decoder.options.DecodeQRCodeRate = null; - disable qrcode decoder
    */
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Demo</title>
    </head>
    <body>
        <h3>Simple initialization with default settings</h3>
        <hr>
        <canvas></canvas>
        <hr>
        <ul></ul>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script language="JavaScript" type="text/javascript" src="/wordpress/wp-content/themes/better-health/webcodecamjs-master/js/qrcodelib.js"></script>
<script language="JavaScript" type="text/javascript" src="/wordpress/wp-content/themes/better-health/webcodecamjs-master/js/webcodecamjs.js"></script>
<!-- 
<script src="/wordpress/wp-content/themes/better-health/webcodecamjs-master/js/webcodecamjquery.js"></script>
<script src="/wordpress/wp-content/themes/better-health/webcodecamjs-master/js/jquery.js"></script>
<script src="/wordpress/wp-content/themes/better-health/webcodecamjs-master/js/DecoderWorker.js"></script>
 -->
  </body>

</html>

And I get the following errors on the console:

Element type must be canvas! webcodecamjs.js:570 Element type must be canvas! teste1:106 Uncaught Referenceerror: $ is not defined at teste1:106 (Anonymous) @teste1:106 webcodecamjs.js:586 GET http://192.168. 0.22/wordpress/index.php/js/Decoderworker.js 404 (Not Found) init @webcodecamjs.js:586 (Anonymous) @teste1:96 teste1:143 GET http://xxx.xxx.x.xx/wordpress/index.php/audio/beep.mp3 404 (Not Found)

1 answer

0

You are using the "webcodecamjs", the way to use is different from the old version "webcodecam" (without the JS at the end).

Old version (link):

$('#qr-canvas').WebCodeCam()

New:

new WebCodeCamJS('#webcodecam-canvas').init();

Behold here

Now the error is "Element type must be canvas! webcodecamjs.js:570" => "On line 570, the element must be a canvas."

In the JS code you have:

 /*---------------------------- Example initializations Javascript version ----------------------------*/
    new WebCodeCamJS("canvas").init(arg);
    /* OR */
    var canvas = document.querySelector('#webcodecam-canvas');
    new WebCodeCamJS(canvas).init();
    /* OR */
    new WebCodeCamJS('#webcodecam-canvas').init();

You should use one of these 3 calls, try using the last one only

new WebCodeCamJS('#webcodecam-canvas').init();

and remove the other two

  new WebCodeCamJS("canvas").init(arg);
        /* OR */
        var canvas = document.querySelector('#webcodecam-canvas');
        new WebCodeCamJS(canvas).init();

and in html add an id to the canvas:

 <canvas id="webcodecam-canvas"></canvas>
  • I edited the question with the code for the new version, but I still receive errors in the console

  • see the response change, I suggest you review the Webcodecamjs documentation more calmly.

  • I deleted and put the id on the canvas, but I still get two errors: Uncaught Referenceerror: args is not defined at teste1:104, in the following line var decoder = $("#webcodecam-canvas").WebCodeCamJQuery(args).data().plugin_WebCodeCamJQuery; and the other mistake GET http://192.168. 0.22/wordpress/index.php/js/Decoderworker.js 404 (Not Found) webcodecamjs.js:586 in the following line DecodeWorker = new Worker(options.decoderWorker);

  • in the example of documentation "args" was not set, so yesterday has "args" leaves blank and "GET 192.168.0.22/wordpress/index.php/js/Decoderworker.js " must be because this file does not exist in this directory.

  • in the library I have this path <script src="/wordpress/wp-content/themes/better-health/webcodecamjs-master/js/DecoderWorker.js"></script>which is correct, and in error returns this path GET 192.168.0.22/wordpress/index.php/js/DecoderWorker.js 404 (Not Found) webcodecamjs.js:586 which are different ways. If the argsand leave blank I get another error Uncaught TypeError: $(...).WebCodeCamJQuery is not a function. I can’t seem to solve these two problems

Browser other questions tagged

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