Skip to content

docans/javascript-barcode

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Dynamsoft JavaScript Barcode SDK

Version 7.0.0

The repository aims to help developers get familiar with Dynamsoft JavaScript Barcode SDK.

This SDK supports decoding 1D, PDF417, QR, DataMatrix, and Aztec barcodes.

The supported data sources include Blob, HTMLImageElement, HTMLVideoElement, URL and more.

You can create a web application or a Node.js application to decode the static images and the video stream within 3 minutes.


Online Demo

Online Demo in Dynamsoft


Browser Compatibility

Windows

Browser Version
Chrome v57+
Firefox v52+
Edge v16+
Opera v44+

Linux

Browser Version
Firefox v52+
Chrome v57+

Mac

Browser Version
Safari* v11+

Safari 11.2.2 ~ 11.2.6 are not supported.

Android

Browser Version
Android webview v57+
Chrome v57+
Firefox v52+

iOS

Browser Version
Safari* v11+

Safari 11.2.2 ~ 11.2.6 are not supported.

Node.js

Version
v8+

Node.js only support BarcodeReader, not support BarcodeScanner.


API Documentation

Decoding Images:

BarcodeReader

Decoding Videos:

BarcodeScanner


Preface

In the following section, we will introduce the basic functions of the SDK and how you can use it in a web application to decode barcodes off a video stream.

For those who are interested in creating a nodejs app, or decoding static images, please refer to the samples and api documents. This guide tackles decoding from a video, and we will make up for other usages soon.


HelloWorld

Before testing the HelloWorld sample, please note that you will require a connected camera that is not occupied by another application, as well as an internet connection.

Now just copy the following code into an html file and run it directly from the browser:

<!DOCTYPE html>
<html>
<body>
    <!--
        Warning: Use a specific version in production. (e.g. https://cdn.jsdelivr.net/npm/dynamsoft-javascript-barcode@x.x.x/dist/dbr.min.js)
        Please visit https://www.dynamsoft.com/CustomerPortal/Portal/TrialLicense.aspx to get trial license.
    -->
    <script src="https://cdn.jsdelivr.net/npm/dynamsoft-javascript-barcode@7/dist/dbr.min.js" data-productKeys="LICENSE-KEY"></script>
    <script>
        let scanner = null;
        Dynamsoft.BarcodeScanner.createInstance({
            onFrameRead: results => {console.log(results);},
            onUnduplicatedRead: (txt, result) => {alert(txt);}
        }).then(s => {
            scanner = s;
            scanner.show();
        });
    </script>
</body>
</html>

Try in JSFiddle


If you open the html as file:/// or http:// You might see the following error after opening the browser console:

[Deprecation] getUserMedia() no longer works on insecure origins. To use this feature, you should consider switching your application to a secure origin, such as HTTPS. See https://goo.gl/rStTGz for more details.

In Safari 12 the same error is displayed as such:

Trying to call getUserMedia from an insecure document.

That is because most browsers today need to be deployed on https to use getUserMedia.

(The latest chrome or Firefox allows getUserMedia when using file:/// or http://localhost. )

Below are some samples for configuring an HTTPS server.

After deploying the site to an https server, the browser might say "the site is not secure". That is because we use self-signed certificates. Please go to the certificate settings and allow this certificate. You may change the certification to a formal one in production.


If everything goes normally, there will be a pop-up from the browser asking for permission of the camera. After allowing access, you will see the video stream in the default UI of our scanner. The drop-down lists on the top left corner can be used for changing the video source and resolution. The button on the top right is for closing the scanner. After all the resources are loaded, you will see some arrays in the browser console. This array is the barcode results array that is being printed in the console once a new frame is read. Now to properly introduce the two main events used by the scanner:

  • onFrameRead:

    The event that is triggered once a single frame has been scanned. The results object contains all the barcode results that the reader was able to decode.

  • onUnduplicatedRead:

    This event is triggered when a new barcode (not a duplicate) is found. txt holds the barcode text result. result contains the actual barcode result, including the text result. Any new barcodes that were found (or any old barcodes that were found) are going to be stored for the duration of duplicateForgetTime.


Initialization

Our library needs some time for initialization, including downloading the resources and compiling them, so you might notice that the decoding process doesn't start immediately. If the HelloWorld sample is deployed, the program will cache the wasm file in the indexedDB to speed the download up.

You can check the download status of the WebAssembly component with the Dynamsoft.BarcodeReader._onWasmDownloaded callback. Please note this function is only triggered during the first visit because that's the only time the wasm files are downloaded.

You need to compile the .wasm file before you can use it. The time it takes to compile depends on the performance of the device and the browser used. It may take a long time on some older devices. For a better user experience, it is recommended that you add some transitions in the process.

Every time you open the page, initialization will take place only once. You can use the isLoaded function to see if the initialization was finished.

loadWasm is the basic function for initialization. You can call loadWasm repeatedly, but loadWasm will only be executed once. The returned promise of loadWasm will be resolved immediately if the initialization is already done.

If you are already sure that the page will use the BarcodeReader or BarcodeScanner, call loadWasm in advance. This way you can enter as soon as you need to use BarcodeReader or BarcodeScanner.

createInstance will call loadWasm on the backend so no initialization is required for those functions. Therefore, it is not necessary to explicitly call loadWasm to initialize the library if you are directly using the constructor.


Debug Info

In case you need to debug your sample application, use the callback _onLog.

Dynamsoft.BarcodeReader._onLog = console.log;

Try in JSFiddle

The log can then be seen in the browser console.


Configuring Scanner Settings

The BarcodeScanner interface comes with a number of properties, some of the most useful being shown here:

// Use config when new the object
let scanner = null;
Dynamsoft.BarcodeScanner.createInstance({
    onFrameRead: results => {console.log(results);},
    onUnduplicatedRead: (txt, result) => {alert(txt);}
}).then(s => {
    scanner = s;

    // Use back camera in mobile. Set width and height.
    // Refer [MediaStreamConstraints](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia#Syntax).
    scanner.setVideoSettings({ video: { width: 1280, height: 720, facingMode: "environment" } });

    let runtimeSettings = scanner.getRuntimeSettings();
    // Only decode OneD and QR
    runtimeSettings.BarcodeFormatIds = Dynamsoft.EnumBarcodeFormat.OneD | Dynamsoft.EnumBarcodeFormat.QR_CODE;
    // The default setting is for an environment with accurate focus and good lighting. The settings below are for more complex environments.
    runtimeSettings.localizationModes = [2,16,4,8,0,0,0,0];
    // Only accept results' confidence over 30
    runtimeSettings.minResultConfidence = 30;
    scanner.updateRuntimeSettings(runtimeSettings);

    let scanSettings = scanner.getScanSettings();
    // The same code awlways alert? Set duplicateForgetTime longer.
    scanSettings.duplicateForgetTime = 20000;
    // Give cpu more time to relax
    scanSettings.intervalTime = 300;
    scanner.setScanSettings(scanSettings);
})

Now that you have seen how to set and change these properties, here is a full list of the properties:

  • UIElement: The HTML element that will contain the video reader object should you choose to customize the UI. We will dig a little deeper into this in the next section.
  • videoSettings: Defines the different settings of the video stream. These settings include the resolution and facing mode. Please visit this link for more information on these video settings.
  • minResultConfidence: This property is mainly related to 1D barcodes. If the confidence of a 1D barcode result is greater than 30, that is a reliable result which you can move forward with. Otherwise, it is recommended that the scan process is restarted so that a more reliable result is produced.
  • intervalTime: The time interval between finding a result and starting a new scan.
  • runtimeSettings: Defines the different settings of the barcode reader itself. Find a full list of these settings and their corresponding descriptions here.
  • duplicateForgetTime: The amount of time the reader "remembers" a barcode result once a single frame is read. Once the barcode result is obtained, the reader will not attempt to read the specific barcode again until duplicateForgetTime is up.

Try in JSFiddle


Configuring RuntimeSettings

fast

let settings = scanner.getRuntimeSettings();
settings.localizationModes = [2,0,0,0,0,0,0,0];
settings.deblurLevel = 0;
scanner.updateRuntimeSettings(settings);

1D

let settings = scanner.getRuntimeSettings();
settings.localizationModes = [2,16,4,8,0,0,0,0];
settings.deblurLevel = 0;
scanner.updateRuntimeSettings(settings);

2D

let settings = scanner.getRuntimeSettings();
settings.localizationModes = [2,16,4,8,0,0,0,0];
settings.deblurLevel = 2;
scanner.updateRuntimeSettings(settings);

Try in JSFiddle

Customize the UI

The Barcode Reader gives you the freedom to use your own UI for the video scanner, and in the next section, we will explore how to configure the reader to allow for custom UI.

Try running the code below.

<!DOCTYPE html>
<html>
<body>
    <div id="div-video-container">
        <video class="dbrScanner-video" playsinline="true"></video>
    </div>
    <!--
        Warning: Use a specific version in production. (e.g. https://cdn.jsdelivr.net/npm/dynamsoft-javascript-barcode@x.x.x/dist/dbr.min.js)
        Please visit https://www.dynamsoft.com/CustomerPortal/Portal/TrialLicense.aspx to get trial license.
    -->
    <script src="https://cdn.jsdelivr.net/npm/dynamsoft-javascript-barcode@7/dist/dbr.min.js" data-productKeys="LICENSE-KEY"></script>
    <script>
        let scanner = null;
        Dynamsoft.BarcodeScanner.createInstance({
            UIElement: document.getElementById('div-video-container'),
            onFrameRead: results => {console.log(results);},
            onUnduplicatedRead: (txt, result) => {alert(txt);}
        }).then(s => {
            scanner = s;
            scanner.show();
        });
    </script>
</body>
</html>

Try in JSFiddle

Now that we have defined the UIElement to be the custom div element, you need to add the video source and resolution dropdown boxes. Here is the HTML element to add a custom video source select dropdown:

<select class="dbrScanner-sel-camera"></select>

Try in JSFiddle

As for adding a resolution select dropdown menu:

<select class="dbrScanner-sel-resolution"></select>

The dropdown will still show the same 8 options for the resolution if you do not manually define the resolution options.

Try in JSFiddle

You can provide limited resolution options to avoid overwhelming the user. Here is the HTML code for how to do that:

<select class="dbrScanner-sel-resolution">
    <!-- <option class="dbrScanner-opt-gotResolution" value="got"></option> -->
    <option data-width="1920" data-height="1080">1920 x 1080</option>
    <option data-width="1280" data-height="720">1280 x 720</option>
    <option data-width="640" data-height="480">640 x 480</option>
</select>

Please note that in this case, you will need to manually dictate the resolution options. If the camera does not support the selected resolution, it will find the closest supported resolution. The "dbrScanner-opt-gotResolution" class option of the dropdown menu (shown above) indicates which resolution is currently being used.

Try in JSFiddle

To play the video at the selected resolution:

scanner.play(null, 1920, 1080).then(r=>{
    alert(r.width+'x'+r.height);
});

Try in JSFiddle

Now suppose you do not want to use either of the select classes listed above for the video source and resolution dropdown boxes. You can use the API methods to populate any HTML element you want to use.

For creating the resolution list, the UI element will need to be manually populated as shown a couple of code snippets ago. Here it is again for reference:

<select class="dbrScanner-sel-resolution">
    <!-- <option class="dbrScanner-opt-gotResolution" value="got"></option> -->
    <option data-width="1920" data-height="1080">1920 x 1080</option>
    <option data-width="1280" data-height="720">1280 x 720</option>
    <option data-width="640" data-height="480">640 x 480</option>
</select>

You can get the device list via the API like this:

scanner.getCurrentCamera().then(info=>{
    // The camera currently in use
    alert(JSON.stringify(info));
});
scanner.getAllCameras().then(infos=>{
    // An array of all cameras
    alert(JSON.stringify(infos, null, 2));
});

Try in JSFiddle

You can play any video source using the deviceId property:

// Play the first camera.
scanner.setCurrentCamera(infos[0].deviceId);

Try in JSFiddle

The video source name that shows up in the dropdown list is taken from the label property rather than the deviceId. It is generally recommended that you use label instead of deviceId because it is more readable. Please note that the camera may display different names in different environments or timings.

If you have more than one connected camera, and would like your application to play a certain one of them on startup, here is how:

scanner.show()
.then(()=>scanner.getAllCamera())
.then(infos=>{
    for(let info of infos){
        if(info.label == 'Your camera name'){
            scanner.setCurrentCamera(info.deviceId);
            break;
        }
    }
});

Try in JSFiddle

How to complete a form using the Barcode Reader

Using HTML code snippet with the custom UI elements, let's add some input tags.

<input id="ipt-0">
<input id="ipt-1">
<input id="ipt-2">

Modify the configuration settings of the video reader to complete the form with the results of three barcodes once they are found:

let iptIndex = 0;
let scanner = null;
Dynamsoft.BarcodeScanner.createInstance({
    UIElement: document.getElementById('div-video-container'),
    onFrameRead: results => {console.log(results);},
    onUnduplicatedRead: (txt)=>{
        document.getElementById('ipt-' + iptIndex).value = txt;
        if(3 == ++iptIndex){
            scanner.onUnduplicatedRead = undefined;
            scanner.stop();
            scanner.hide();
        }
    }
}).then(s => {
    scanner = s;
    scanner.show();
});

Try in JSFiddle


Decode Part of Video

If you are not interested in exhausting resources to read the entire area of the video stream, you can choose to decode a specific region of the stream. Here is how:

// Ignore around 25% while decoding
let settings = scanner.getRuntimeSettings();
settings.region.left = 25;
settings.region.top = 25;
settings.region.right = 25;
settings.region.bottom = 25;
settings.region.measuredByPercentage = 1; // 1 means true
scanner.updateRuntimeSettings(settings);

Try in JSFiddle


Self Deployment

In the HelloWorld sample, you used the min.js hosted on CDN, which can load the other required js and wasm files.

Most of the time you use this cdn is enough, it is fast and stable.

But sometimes you will want to deploy it yourself, for example, in an environment without Internet, for example, you can provide a faster and more stable CDN.


To deploy resources yourself, you will need a web server and deploy the resources under a folder named dist to your server.

Required files in dist:

dbr-<version>.min.js
dbr-<version>.wasm.min.js
dbr-<version>.wasm
dbr-<version>.wasm.withio.min.js
dbr-<version>.withio.wasm
dbr-<version>.esm.min.js

It is recommended that you bring all these files with you when you use them. But if you want to reduce the files you need to deploy, here is a rough list of the necessary files:

  • web + document + UMD:
dbr-<version>.min.js
dbr-<version>.wasm.min.js
dbr-<version>.wasm
  • web + worker + UMD:
dbr-<version>.min.js
dbr-<version>.wasm.withio.min.js
dbr-<version>.withio.wasm
  • web + document + es6 module:
dbr-<version>.min.esm.js
dbr-<version>.wasm.min.js
dbr-<version>.wasm
  • web + worker + es6 module:
dbr-<version>.min.esm.js
dbr-<version>.wasm.withio.min.js
dbr-<version>.withio.wasm
  • nodejs + UMD:
dbr-<version>.min.js
dbr-<version>.wasm.withio.min.js
dbr-<version>.withio.wasm

You need to set .wasm mimetype to application/wasm in the server config.

Please check the settings below for different environments.


Changelog

6.5.2.1

Improve video decoding capabilities.

6.5.2

Built Dynamsoft Barcode Reader 6.5.2 to JS(WebAssembly) version.

Walkaround for certain scenarios of Content Security Policy (CSP).

Add a setting can turn off the feature of using IndexedDB.

6.5.1

Added video view for barcode scan. Compatible with Node.js.

6.4.1.3

The dbr-6.4.1.3.wasm size is now reduced to 3.41M.

6.4.1.1

Fixed a memory leak related to mTimeout in RuntimeSettings.

6.4.1.0

Built Dynamsoft Barcode Reader 6.4.1 to JS(WebAssembly) version.

Combined the normal and the mobile version into one.

6.3.0.2

Added built-in Worker support.

6.3.0.1

Set dbr-<version>.js(stable) as the main branch.

Added dbr-<version>.mobile.js(smaller, compiles quicker, requires less memory, but not as stable) for mobile Safari.

6.3.0

Built Dynamsoft Barcode Reader 6.3.0 to JS(WebAssembly) version.


Contact Us

If there are any questions, please feel free to contact support@dynamsoft.com.

License Agreement

https://www.dynamsoft.com/Products/barcode-reader-license-agreement.aspx#javascript

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • HTML 90.5%
  • CSS 9.5%