How to Build a Live Barcode Scanner Using Webcam in Javascript

Want to build a live barcode scanner using a webcam in JavaScript but don’t know where to start? Well, you have arrived at the right place! In this article, we will share an easy way to do so.

So, without further ado, let’s get started!

Easy way to create live barcode scanner

Developing codes to build a live barcode scanner is a time consuming task. Of course, you also need good programming experience.

On the other hand, choosing Barcode Scanner SDK will save you time and effort, as you only need a few lines of JavaScript code to build a barcode reader app. There are many benefits to be found with the Barcode Reader SDK. Some important ones are listed below.

  • Easy to integrate: One of the most exciting benefits of the Barcode Reader SDK is that it is easy to integrate. You only need a few lines of code, and you can add barcode reading functionality to an existing or new app.

  • Customization Capabilities: Another great advantage of choosing Barcode Reader SDK is that you can customize the features as per your needs. Unlike those off-the-shelf solutions that offer a fixed set of features and functionalities, you can choose from different APIs and optimize as needed. Leading solutions provide hundreds of APIs to choose from.

  • Saves time and effort: With Barcode Reader SDK, you don’t have to spend much time and effort developing those complicated barcode scanning codes. All this has already been done for you. Whether you have a huge team of developers or not, you are good to go.

  • Technical support for quick solution: Whether you are facing a problem or have difficulty understanding a feature or functionality, your vendor’s technical experts can assist you.

Choosing a JavaScript Barcode Scanner SDK

How do you choose the best SDK for your application? Well, the pointers given below will help you.

  • high speed: You don’t want to build a barcode reader that is slow. Therefore, it becomes important that you invest in a barcode scanning SDK which provides good decoding speed. Top performing solutions support reading over 500 barcodes a minute.

  • Excellent Accuracy: Look for a solution that deploys a commercial-grade barcode detection algorithm, camera-enhancing functionality, and OCR capabilities to deliver exceptional accuracy.

  • Rich UI Elements: The Barcode Reader SDK should be easy to use. Therefore, make sure that the SDK you choose offers rich UI elements to provide a good barcode scanning experience.

  • Supported Platforms and Languages: Barcode scanning is mandatory to go through the OS, Platforms and Languages ​​supported by the SDK. Since you want to build a live barcode scanner using webcam in JavaScript, you should look for a JavaScript Barcode Scanner SDK. Also see what browsers it supports.

  • Supports multiple barcode symbols: Whether you want to read QR codes, PDF417 codes, or one-dimensional barcodes, the barcode reader SDK you choose must support standard barcode symbology.

  • Reads hard barcodes: Most common barcode readers fail to read difficult barcodes such as incomplete, torn, wrinkled, dense or skewed. Therefore, look for a barcode scanning SDK that can easily decode such barcodes.

  • Works well in challenging environments: Shadows, glare or low light will make it difficult for a normal barcode scanner to read the barcode. Invest in a barcode reader SDK that can perform well in all such situations.

  • Offers Online Demo and Free Trial: It is important that you test the product before making a purchase. Check out the online demo for a quick look, and download a free trial for extensive research before making a decision.

Now that you are familiar with the important features to look for in the Barcode Reader SDK, you can make a good selection. You can try out different options to see which one best suits your needs.

Build Live Barcode Scanner Using Webcam in Javascript

Let’s build a real-time web barcode reader app with webcam. We will be using Dynasoft JavaScript Barcode Reader SDK in this project.

Camera-Based Web Barcode Scanning Component

First of all, you need to download and open React-webcam.js.

See the render() function to add a canvas and a button. The button is used to trigger a barcode scan and then render the barcode result on the canvas:

render() {

    return (

      <div id='videoview' width={this.props.width} height={this.props.height}>

        <button onClick={this.scanBarcode}>Scan Barcodes</button>

        <video

          autoPlay

          width={this.props.width}

          height={this.props.height}

          src={this.state.src}

          muted={this.props.audio}

          className={this.props.className}

          playsInline

          style={this.props.style}

          ref={(ref) => {

            this.video = ref;

          }}

        />

        <canvas id="overlay" width={this.props.width} height={this.props.height}></canvas>

      </div>

    );

  }

Now, in order to display the result on the video, we have to make adjustments to the styles of the HTML elements. Let’s create a react-webcam.css file:

#videoview {

    position: relative;

    width: 640px;

    height: 480px;

  }

 

#video {

    position: relative;

    width: 100%;

    height: 100%;

    z-index: 1

}

 

#overlay {

    position: absolute;

    top: 100;

    left: 0;

    width: 100%;

    height: 100%;

    z-index: 2

}

Let’s now import the CSS file into the react-webcam.js file:

import React, { Component } from 'react';

import PropTypes from 'prop-types';

import './react-webcam.css';

Create a scanBarcode() function, in which we need to get a byte array of video frames. Next, we have to call the decodeBuffer() method:

scanBarcode() {

    if (window.reader) {

      let canvas = document.createElement('canvas');

      canvas.width = this.props.width;

      canvas.height = this.props.height

      let ctx = canvas.getContext('2d');

      ctx.drawImage(this.video, 0, 0, this.props.width, this.props.height);

     

      window.reader.decodeBuffer(

        ctx.getImageData(0, 0, canvas.width, canvas.height).data,

        canvas.width,

        canvas.height,

        canvas.width * 4,

        window.dynamsoft.BarcodeReader.EnumImagePixelFormat.IPF_ARGB_8888

      )

      .then((results) => {

        this.showResults(results);

      });

    }

     

  }

To initialize window.reader , create an instance of BarcodeReader and make it globally accessible once the wasm file is loaded into public/index.html :

<body>

    <img src="http://dzone.com/articles/loading.gif" style="margin-top:10px" id="anim-loading">

    <script src="https://demo.dynamsoft.com/dbr_wasm/js/dbr-6.4.1.3.min.js"></script>

    <script>

      dynamsoft.dbrEnv.resourcesPath="https://demo.dynamsoft.com/dbr_wasm/js";

      dynamsoft.dbrEnv.onAutoLoadWasmSuccess = function () {

        window.reader = new dynamsoft.BarcodeReader();

        window.dynamsoft = dynamsoft;

        document.getElementById('anim-loading').style.display = 'none';

      };

      dynamsoft.dbrEnv.onAutoLoadWasmError = function (ex) {

        document.getElementById('anim-loading').style.display = 'none';

        alert('Fail to load the wasm file.');

      };

      dynamsoft.dbrEnv.bUseWorker = true;

 

      // Get a free trial license from https://www.dynamsoft.com/customer/license/trialLicense/

      dynamsoft.dbrEnv.licenseKey = "Your Barcode SDK License"

 

    </script>

    <div id="root"></div>

Important: dynamicsoft.dbrEnv.bUseWorker must be true.

To make this work in scanBarCode(), we need to bind it in the constructor:

constructor() {

  super();

  this.state = {

  hasUserMedia: false,

};

this.scanBarcode = this.scanBarcode.bind(this);

}

The code below will help you understand how to continuously scan and display barcode results on webcam video:

, } } “data-lang”>

showResults(results) {

    let context = this.clearOverlay();

    let txts = [];

    try {

      let localization;

      for (var i = 0; i < results.length; ++i) {

        if (results[i].LocalizationResult.ExtendedResultArray[0].Confidence >= 30) {

          txts.push(results[i].BarcodeText);

          localization = results[i].LocalizationResult;

          this.drawResult(context, localization, results[i].BarcodeText);

        }

      }

       

      this.scanBarcode();

       

    } catch (e) {

      this.scanBarcode();

    }

  }

 

clearOverlay() {

    let context = document.getElementById('overlay').getContext('2d');

    context.clearRect(0, 0, this.props.width, this.props.height);

    context.strokeStyle="#ff0000";

    context.lineWidth = 5;

    return context;

  }

   

drawResult(context, localization, text) {

    context.beginPath();

    context.moveTo(localization.X1, localization.Y1);

    context.lineTo(localization.X2, localization.Y2);

    context.lineTo(localization.X3, localization.Y3);

    context.lineTo(localization.X4, localization.Y4);

    context.lineTo(localization.X1, localization.Y1);

    context.stroke();

   

    context.font="18px Verdana";

    context.fillStyle="#ff0000";

    let x = [ localization.X1, localization.X2, localization.X3, localization.X4 ];

    let y = [ localization.Y1, localization.Y2, localization.Y3, localization.Y4 ];

    x.sort(function(a, b) {

      return a - b;

    });

    y.sort(function(a, b) {

      return b - a;

    });

    let left = x[0];

    let top = y[0];

   

    context.fillText(text, left, top + 50);

  }



Let's open App.js to add the React webcam component:



import React, { Component } from 'react';

import logo from './logo.svg';

import './App.css';

import {Barcode} from './Barcode';

import Webcam from './react-webcam';

 

class App extends Component {

  render() {

    return (

      <div className="App">

        <Barcode/>

        <Webcam />

      </div>

    );

  }

}

Leave a Comment