-1

Estou a utilizar o WebCodeCam para detetar e escanear o valor de um código de barras ou código QR apresentado na frente da webcam. Uma função de retorno de chamada é invocada quando a imagem é Código de barras ou o código QR é decodificado. Também pode controlar o nível de zoom capturado, brilho da imagem, contraste, nitidez, limite, 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>

Mas quando executo a página, recebo o seguinte erro na console:

Uncaught TypeError: $(...).WebCodeCam is not a function at teste1:57

Edição:

Ajustei o meu código à versão recente mas ainda não funciona:

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>

E recebo os seguintes erros na consola:

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 Resposta 1

-1

Você está utilizando o "webcodecamjs", a forma de utilizar é diferente da versão antiga "webcodecam" (sem o JS no final).

Versão antiga (link):

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

Nova:

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

Veja aqui

Agora o erro é "Element type must be canvas! webcodecamjs.js:570" => "Na linha 570, o elemento deve ser um canvas."

No codigo JS tem:

 /*---------------------------- 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();

Você deve usar uma dessas 3 chamadas, tente usar a ultima somente

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

e remova as outras duas

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

e no html adicione um id para o canvas:

 <canvas id="webcodecam-canvas"></canvas>
5
  • editei a pergunto com o código para a nova versão, mas continuo a receber erros na consola
    – Bruno
    21/03/2019 às 14:10
  • veja a alteração da resposta, indico que reveja a documentação do WebCodeCamJS com mais calma.
    – RDyego
    21/03/2019 às 14:19
  • eliminei e coloquei o id no canvas, mas continuo a receber dois erros: Uncaught ReferenceError: args is not defined at teste1:104, na seguinte linha ` var decoder = $("#webcodecam-canvas").WebCodeCamJQuery(args).data().plugin_WebCodeCamJQuery;` e o outro erro GET 192.168.0.22/wordpress/index.php/js/DecoderWorker.js 404 (Not Found) webcodecamjs.js:586 na seguinte linha DecodeWorker = new Worker(options.decoderWorker);
    – Bruno
    21/03/2019 às 14:41
  • no exemplo da documentação "args" não foi definido, então ontem tem "args" deixa em branco e "GET 192.168.0.22/wordpress/index.php/js/DecoderWorker.js " deve ser por causa que esse arquivo não existe nesse diretório.
    – RDyego
    21/03/2019 às 14:44
  • na biblioteca tenho este caminho <script src="/wordpress/wp-content/themes/better-health/webcodecamjs-master/js/DecoderWorker.js"></script>que é o correto, e no erro retorna este caminho GET 192.168.0.22/wordpress/index.php/js/DecoderWorker.js 404 (Not Found) webcodecamjs.js:586 que são caminhos diferentes.Se retirar o argse deixar em branco recebo outro erro Uncaught TypeError: $(...).WebCodeCamJQuery is not a function. Não estou a conseguir resolver estes dois problemas
    – Bruno
    21/03/2019 às 16:11

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .