Select Page

How to Create a Live Barcode Scanner Using the Webcam in JavaScript

Eric Parker
Published: November 11, 2022

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

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

The Easier Way to Build a Live Barcode Scanner 

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

On the other hand, choosing a 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. Multiple benefits come along with a barcode reader SDK. Some of the important ones are listed below. 

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

  • Customization Capabilities: Another brilliant advantage of choosing a barcode reader SDK is that you can customize features per your requirements. Unlike those off-the-shelf solutions that offer a fixed set of features and functionalities, you can choose from different APIs and make customization as and when required. Leading solutions provide hundreds of APIs to choose from. 

  • Saves Time and Effort: With a barcode reader SDK, you don’t have to spend much time and effort developing those complex barcode scanning codes. All this is already done for you. Whether you have a massive team of developers or not, you are good to go. 

  • Technical Support for Quick Resolution: Whether you’re facing an issue or finding it difficult to understand some feature or functionality, the technical experts at your vendor can help you out. 

Choosing a JavaScript Barcode Scanner SDK 

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

  • Fast Speed: You wouldn’t want to build a barcode reader that is slow. Hence, it becomes crucial that you invest in a barcode scanning SDK that offers good decoding speed. Top-performing solutions support reading over 500 barcodes in a minute.

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

  • Rich UI Elements: The barcode reader SDK should be easy to use. Hence, make sure the SDK you choose must offer rich UI elements to offer a good barcode scanning experience. 

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

  • Supports Multiple Barcode Symbologies: Whether you want to read QR codes, PDF417 codes, or one-dimensional barcodes, the barcode reader SDK you choose must support standard barcode symbologies

  • Reads Tough Barcodes: Most ordinary barcode readers fail to read tough barcodes such as incomplete, torn, wrinkled, dense, or skewed. Hence, look for a barcode scanning SDK that easily decodes such types of barcodes. 

  • Works Well in Challenging Environments: Shadow, glare, or low light will make barcode reading difficult for ordinary barcode scanners. Invest in a barcode reader SDK that can perform well in all such conditions. 

  • Offers Online Demos and Free Trials: It is crucial that you try the product before making a purchase. Check out the online demo for a quick look, and download free trials for extensive research before you make a decision. 

Now that you have become familiar with the important features to look for in a barcode reader SDK, you can make a good selection. You may try different options to see which one suits your requirements the most. 

Building a Live Barcode Scanner Using the Webcam in JavaScript

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

Camera-Based Web Barcode Scanning Component

First, you need to download and open react-webcam.js.

Look for the render() function so as to add a canvas and a button. The button is used to trigger the barcode scan and then render barcode results 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, to display the results on the video, we’ll have to make adjustments in the styles of the HTML elements. Let’s build 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 import the CSS file in the react-webcam.js file now: 

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import './react-webcam.css';

Build a scanBarcode() function, in which we’ll have to get the byte array of the video frame. Next, we’ll 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 the window.reader, create an instance of the barcode reader and make it globally accessible once the wasm file is loaded in public/index.html: 

<body>
    <img src="https://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: dynamsoft.dbrEnv.bUseWorker has to be true. 

To make this work in scanBarcode(), we’ll have to bind it in the constructor:

constructor() {
  super();
  this.state = {
  hasUserMedia: false,
};
this.scanBarcode = this.scanBarcode.bind(this);
}

The below code will help you understand how to continuously scan and display the barcode results on the 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>
    );
  }
}

Source: dzone.com