Resource Base
Table of contents

Thanks for downloading Dynamsoft Barcode Reader Package!

Your download will start shortly. If your download does not begin, click here to retry.

BarcodeScanner for Video

A barcode scanner object gets access to a camera via the MediaDevices interface, then uses its built-in UI to show the camera input and perform continuous barcode scanning on the incoming frames.

The default built-in UI of each barcode scanner is defined in the file “dbr.scanner.html”. If used directly, the UI will fit the entire page and sit on top. There are a few ways to customize it, read more on how to Customize the UI.

Although a barcode scanner is designed to scan barcodes from a video input, it also supports a special mode called singleFrameMode which allows the user to select a still image or take a shot with the mobile camera for barcode scanning.

The BarcodeScanner is a child class of BarcodeReader and inherits all its methods and properties which will not be covered in this article.

The following code snippet shows the basic usage of the BarcodeScanner class.

let scanner = await Dynamsoft.DBR.BarcodeScanner.createInstance();
scanner.onUnduplicatedRead = txt => console.log(txt);
await scanner.show();

API Index

Create and Destroy Instances

API Name Description
createInstance Creates a BarcodeScanner instance.
destroyContext Destroys the BarcodeScanner instance.
isContextDestroyed Indicates whether the instance has been destroyed.

Decode Barcodes

API Name Description
onUnduplicatedRead This event is triggered when a new, unduplicated barcode is found.
onFrameRead This event is triggered after the library finishes scanning a frame.

Basic Interaction

API Name Description
show Binds and shows UI, opens the camera and starts decoding.
hide Stops decoding, releases camera and unbinds UI.
open Binds UI, opens the camera and starts decoding. Meant for use with frameworks like Angular, Vue, React.
close Stops decoding, releases camera and unbinds UI. Meant for use with frameworks like Angular, Vue, React.

Scan Settings

API Name Description
whenToPlaySoundforSuccessfulRead Sets when to play sound on barcode recognition.
soundOnSuccessfullRead Specifies the sound to play on barcode recognition.
whenToVibrateforSuccessfulRead Sets when to vibrate on barcode recognition.
vibrateDuration Returns or sets how long the vibration lastsin milliseconds.
singleFrameMode Returns or sets whether to enable the singe-frame mode.
getScanSettings Returns the current scan settings.
updateScanSettings Changes scan settings with the object passed in.

UI Control

API Name Description
getUIElement Returns the HTML element that is used by the BarcodeScanner instance.
setUIElement Specifies an HTML element for the BarcodeScanner instance to use as its UI.
defaultUIElementURL Returns or sets the URL of the .html file that defines the default UI Element.
barcodeFillStyle Specifies the color used inside the shape which highlights a found barcode.
barcodeStrokeStyle Specifies the color used to paint the outline of the shape which highlights a found barcode.
barcodeLineWidth Specifies the line width of the outline of the shape which highlights a found barcode.
regionMaskFillStyle Specifies the color used in the square-loop shape between the actual scanning area and the boundary of the video input.
regionMaskStrokeStyle Specifies the color used to paint the outline of the scanning region.
regionMaskLineWidth Specifies the width of the outline of the scanning region.

Camera Control

API Name Description
getAllCameras Returns infomation of all available cameras on the device.
getCurrentCamera Returns information about the current camera.
setCurrentCamera Chooses a camera as the video source.
getResolution Returns the resolution of the current video input.
setResolution Sets the resolution of the current video input.
getVideoSettings Returns the current video settings.
updateVideoSettings Changes the video input.

Video Decoding Process Control

API Name Description
play Play the video if it is already open but paused or stopped.
onPlayed This event is triggered when the video stream starts playing.
pauseScan Pauses the decoding process.
resumeScan Resumes the decoding process.
pause Pauses the video without releasing the camera.
stop Stops the video and releases the camera.

Advanced Camera Control

API Name Description
getCapabilities Inspects and returns the capabilities of the current camera.
getCameraSettings Returns the current values for each constrainable property of the current camera.
setFrameRate Adjusts the frame rate.
setColorTemperature Adjusts the color temperature.
setExposureCompensation Sets the exposure compensation index.
setZoom Sets the zoom level of the camera.
turnOnTorch Turns on the torch/flashlight.
turnOffTorch Turns off the torch/flashlight.

Inherited from the BarcodeReader Class

Decode Barcodes from Images/Base64 Strings/URL/Buffer

API Name Description
decode Decodes barcodes from an image.
decodeBase64String Decodes barcodes from a base64-encoded image (with or without MIME).
decodeUrl Decodes barcodes from an image specified by its URL.
decodeBuffer Decodes barcodes from raw image data.

Change Settings

API Name Description
getRuntimeSettings Returns the current runtime settings.
updateRuntimeSettings Updates runtime settings with a given struct or a preset template.
resetRuntimeSettings Resets all parameters to default values.
getModeArgument Returns the argument value for the specified mode parameter.
setModeArgument Sets the argument value for the specified mode parameter.

Auxiliary

API Name Description
ifSaveOriginalImageInACanvas Whether to save the original image into a <canvas> element.
getOriginalImageInACanvas Returns an HTMLCanvasElement that holds the original image.

createInstance

Creates a BarcodeScanner instance.

static createInstance(): Promise<BarcodeScanner>

Parameters

None.

Return value

A promise resolving to the created BarcodeScanner object.

Code Snippet

let scanner = await Dynamsoft.DBR.BarcodeScanner.createInstance();

destroyContext

Destroys the BarcodeScanner instance. If your page needs to create a new instance from time to time, don’t forget to destroy unused old instances.

destroyContext(): Promise<void>

Parameters

None.

Return value

A promise that resolves when the operation succeeds.

Code Snippet

let scanner = await Dynamsoft.DBR.BarcodeScanner.createInstance();
// ... decode ...
scanner.destroyContext();

isContextDestroyed

Returns whether the instance has been destroyed.

isContextDestroyed(): boolean

onUnduplicatedRead

Specifies an event handler which fires when a new, unduplicated barcode is found.

The library keeps each barcode result (type and value) in the buffer for a period of time (can be set with duplicateForgetTime) during which if a new result is an exact match, it’s seen as a duplicate and will again be kept for that period of time while the old result is removed and so on.

onUnduplicatedRead: (txt: string, result: TextResult) => void

Arguments

txt : a string that holds the barcode text.

result : a TextResult object that contains more detailed info.

Code Snippet

scanner.onUnduplicatedRead = (txt, result) => {
    alert(txt);
    console.log(result);
}

See also

onFrameRead

Specifies an event handler which fires after the library finishes scanning a frame.

onFrameRead: (results: TextResult[]) => void

Arguments

results : a TextResult object that contains all the barcode results in this frame.

Code Snippet

scanner.onFrameRead = results => {
    for (let result of results) {
        console.log(result.barcodeText);
    }
};

See also

show

Binds and shows UI, opens the camera and starts decoding.

show(): Promise<ScannerPlayCallbackInfo>

Parameters

None.

Return value

A promise resolving to a ScannerPlayCallbackInfo object.

Code Snippet

scanner.onUnduplicatedRead = (txt, result) => {
    alert(txt);
    console.log(result);
};
await scanner.show();

See also

hide

Stops decoding, releases camera and unbinds UI.

hide(): Promise<void>

Parameters

None.

Return value

A promise that resolves when the operation succeeds.

Code Snippet

await scanner.show();
//...scan barcodes
await scanner.hide();

open

Binds UI, opens the camera and starts decoding. Meant for use with frameworks like Angular, Vue, React.

open(): Promise<void>

Parameters

None.

Return value

A promise that resolves when the operation succeeds.

Code Snippet

await scanner.open();
//...scan barcodes
await scanner.close();

close

Stops decoding, releases camera and unbinds UI. Meant for use with frameworks like Angular, Vue, React.

close(): Promise<void>

Parameters

None.

Return value

A promise that resolves when the operation succeeds.

Code Snippet

await scanner.open();
//...scan barcodes
await scanner.close();

pauseScan

Pauses the decoding process.

`` `typescript pauseScan(): void


**Parameters**

None.

**Return value**

None.

## resumeScan

Resumes the decoding process.

```typescript
resumeScan(): void

Parameters

None.

Return value

None.

whenToPlaySoundforSuccessfulRead

Sets when to play sound on barcode recognition (user input is required on iOS or Chrome for any sound to play). Allowed values are

  • never: never play sound, the default value;
  • frame: play sound when one or multiple barcodes are found on a frame;
  • unduplicated: play sound when a unique/unduplicated barcode is found (if multiple unique barcodes are found on the same frame, play only once).
whenToPlaySoundforSuccessfulRead: (boolean | string)

Default value

false

Code Snippet

// A user gesture required. 
startPlayButton.addEventListener('click', function() {
    scanner.whenToPlaySoundforSuccessfulRead = true;
});

soundOnSuccessfullRead

Specifies the sound to play on barcode recognition. If not specified, the default one is used.

soundOnSuccessfullRead: HTMLAudioElement

Code Snippet

scanner.soundOnSuccessfullRead = new Audio("./pi.mp3");

See also

whenToVibrateforSuccessfulRead

Sets when to vibrate on barcode recognition (user input is required on iOS or Chrome for the vibration). Allowed values are

  • never: never vibrate, the default value;
  • frame: vibrate when one or multiple barcodes are found on a frame;
  • unduplicated: vibrate when a unique/unduplicated barcode is found (if multiple unique barcodes are found on the same frame, vibrate only once).
whenToVibrateforSuccessfulRead: (boolean | string)

Default value

false

Code Snippet

// Can I use? https://caniuse.com/?search=vibrate
startVibrateButton.addEventListener('click', function() {
    scanner.whenToVibrateforSuccessfulRead = true;
});

vibrateDuration

Returns or sets how long the vibration lasts in milliseconds. The default value is 300 .

vibrateDuration: number

See also

singleFrameMode

Returns or sets the status of the single-frame mode. If enabled, the video input will not be played and the user can choose to take a picture with the system camera or select an existing image for barcode reading.

The single-frame mode can only be enabled or disabled before the video input starts playing.

singleFrameMode: boolean

getScanSettings

Returns the current scan settings.

getScanSettings(): Promise<ScanSettings>

Parameters

None.

Return value

A promise resolving to a ScanSettings .

Code Snippet

let scanSettings = await scanner.getScanSettings();
scanSettings.intervalTime = 50;
scanSettings.duplicateForgetTime = 1000;
await scanner.updateScanSettings(scanSettings);

See also

updateScanSettings

Changes scan settings with the object passed in.

updateScanSettings(settings: ScanSettings): Promise<void>

Parameters

settings : specifies the new scan settings.

Return value

A promise that resolves when the operation succeeds.

Code Snippet

let scanSettings = await scanner.getScanSettings();
scanSettings.intervalTime = 50;
scanSettings.duplicateForgetTime = 1000;
await scanner.updateScanSettings(scanSettings);

See also

getUIElement

Returns the HTML element that is used by the BarcodeScanner instance.

getUIElement(): HTMLElement

setUIElement

Specifies an HTML element for the BarcodeScanner instance to use as its UI. The structure inside the element determines the appearance of the UI. See more on how to customize the UI.

setUIElement(elementOrURL: HTMLElement | string): Promise<void>

Parameters

elementOrURL : specifies the element.

Return value

A promise that resolves when the operation succeeds.

Code Snippet

<!-- Define an element that shows only the video input -->
<video class="dbrScanner-video" playsinline="true"></video>
<script>
    let scanner = await Dynamsoft.DBR.BarcodeScanner.createInstance();
    await scanner.setUIElement(document.getElementsByClassName("dbrScanner-video")[0]);
    await scanner.open();
</script>
<!-- Use the default official UI element definition -->
<script>
    let scanner = await Dynamsoft.DBR.BarcodeScanner.createInstance();
    await scanner.setUIElement("https://cdn.jsdelivr.net/npm/dynamsoft-javascript-barcode@8.8.3/dist/dbr.scanner.html");
    await scanner.show();
</script>

defaultUIElementURL

Returns or sets the URL of the .html file that defines the default UI Element. The URL can only be set before the API createInstance is called.

static defaultUIElementURL: string

Code Snippet

Dynamsoft.DBR.BarcodeScanner.defaultUIElementURL = "https://cdn.jsdelivr.net/npm/dynamsoft-javascript-barcode@8.8.3/dist/dbr.scanner.html";
let scanner = await Dynamsoft.DBR.BarcodeScanner.createInstance();
await scanner.show();

barcodeFillStyle

Specifies the color used inside the shape which highlights a found barcode. The default value is rgba(254, 180, 32, 0.3) .

barcodeFillStyle: string

barcodeStrokeStyle

Specifies the color used to paint the outline of the shape which highlights a found barcode. The default value is rgba(254, 180, 32, 0.9) .

barcodeStrokeStyle: string

barcodeLineWidth

Specifies the line width of the outline of the shape which highlights a found barcode. The default value is 1 .

barcodeLineWidth: number

regionMaskFillStyle

Specifies the color used in the square-loop shape between the actual scanning area and the boundary of the video input. This shape only appears when the barcode scanning is limited to a specified region. The default value is rgba(0, 0, 0, 0.5) .

regionMaskFillStyle: string

See also

regionMaskStrokeStyle

Specifies the color used to paint the outline of the scanning region. This outline only appears when the barcode scanning is limited to a specified region. The default value is rgb(254, 142, 20) .

regionMaskStrokeStyle: string

See also

regionMaskLineWidth

Specifies the width of the outline of the scanning region. This outline only appears when the barcode scanning is limited to a specified region. The default value is 2 .

regionMaskLineWidth: number

See also

getAllCameras

Returns infomation of all available cameras on the device.

getAllCameras(): Promise<VideoDeviceInfo[]>

Parameters

None.

Return value

A promise resolving to an array of VideoDeviceInfo objects.

Code Snippet

let cameras = await scanner.getAllCameras();
if (cameras.length) {
    await scanner.setCurrentCamera(cameras[0]);
}

See also

getCurrentCamera

Returns information about the current camera.

getCurrentCamera(): Promise<VideoDeviceInfo | null>

Parameters

None.

Return value

A promise resolving to a VideoDeviceInfo object.

Code Snippet

let camera = await scanner.getCurrentCamera();

See also

setCurrentCamera

Chooses a camera as the video source.

setCurrentCamera(deviceID: string): Promise<ScannerPlayCallbackInfo>

Parameters

deviceID : specifies the camera.

Return value

A promise resolving to a ScannerPlayCallbackInfo object.

Code Snippet

let cameras = await scanner.getAllCameras();
if (cameras.length) {
    await scanner.setCurrentCamera(cameras[0]);
}

See also

getResolution

Returns the resolution of the current video input.

getResolution(): number[]

Parameters

None.

Return value

An array of two numbers representing the resolution.

Code Snippet

let rsl = await scanner.getResolution();
console.log(rsl.width + " x " + rsl.height);

setResolution

Sets the resolution of the current video input. If the specified resolution is not exactly supported, the closest resolution will be applied.

setResolution(width: number, height: number): Promise<ScannerPlayCallbackInfo>

Parameters

width : specifies the horizontal resolution. height : specifies the vertical resolution.

To speed up the barcode scanning, the image frames will be scaled down when it exceeds a size limit either horizontally or vertically. The limit is 2048 pixels on mobile devices and 4096 on other devices. Therefore, setting a very high resolution will not help with the scanning.

Return value

A promise resolving to a ScannerPlayCallbackInfo object.

Code Snippet

await scanner.setResolution(width, height);

See also

getVideoSettings

Returns the current video settings.

getVideoSettings(): MediaStreamConstraints

Parameters

None.

Return value

A MediaStreamConstraints object.

See also

updateVideoSettings

Changes the video input.

updateVideoSettings(constraints: MediaStreamConstraints): Promise<ScannerPlayCallbackInfo | void>

Parameters

constraints : specifies the new video settings.

Return value

A promise resolving to a ScannerPlayCallbackInfo object.

Code Snippet

await scanner.updateVideoSettings({
    video: {
        width: {
            ideal: 1280
        },
        height: {
            ideal: 720
        },
        facingMode: {
            ideal: 'environment'
        }
    }
});

See also

play

Play the video if it is already open but paused or stopped. If the video is already playing, it will start again.

play(): Promise<ScannerPlayCallbackInfo>

Parameters

None.

Return value

A promise resolving to a ScannerPlayCallbackInfo object.

Code Snippet

scanner.pause();
//..doing other things without the video
await scanner.play();

See also

onPlayed

This event is triggered when the video stream starts playing.

event onPlayed: (info: ScannerPlayCallbackInfo) => void

Arguments

info: a ScannerPlayCallbackInfo object which describes the resolution of the video input.

Code Snippet

scanner.onplayed = rsl => {
    console.log(rsl.width + 'x' + rsl.height)
};
await scanner.show(); // or open(), play(), setCurrentCamera(), etc.

See also

pause

Pauses the video without releasing the camera.

pause(): void

Parameters

None.

Return value

None.

stop

Stops the video and releases the camera.

stop(): void

Parameters

None.

Return value

None.

getCapabilities

Inspects and returns the capabilities of the current camera.

Right now, this method only works in Chrome and should be called when the scanner is open.

getCapabilities(): MediaTrackCapabilities

Parameters

None.

Return value

A MediaTrackCapabilities object which specifies the values or range of values for each constrainable property of the current camera.

Code Snippet

scanner.getCapabilities();
/* Result sample
{
  aspectRatio: {max: 1280, min: 0.001388888888888889},
  brightness: {max: 64, min: -64, step: 1},
  colorTemperature: {max: 6500, min: 2800, step: 10},
  contrast: {max: 95, min: 0, step: 1},
  deviceId: "3a505c29a3312600ea0afd79f8e2b4ba4fba3e539257801ff1de8718c27f2bed",
  exposureMode: ["continuous", "manual"],
  exposureTime: {max: 10000, min: 39.0625, step: 39.0625},
  facingMode: [],
  focusDistance: {max: 1024, min: 0, step: 10},
  focusMode: ["continuous", "manual"],
  frameRate: {max: 30, min: 0},
  groupId: "35a82dcb7d5b0ef5bda550718d194f04a812c976175e926ccb81fb9d235d010f",
  height: {max: 720, min: 1},
  resizeMode: ["none", "crop-and-scale"],
  saturation: {max: 100, min: 0, step: 1},
  sharpness: {max: 7, min: 1, step: 1},
  whiteBalanceMode: ["continuous", "manual"],
  width: {max: 1280, min: 1}
}
*/

See also

getCameraSettings

Returns the current values for each constrainable property of the current camera.

Right now, this method only works in Chrome and should be called when the scanner is open.

getCameraSettings(): any

Parameters

None.

Return value

The current values for each constrainable property of the current camera

Code Snippet

scanner.getCameraSettings();
/* Result sample
{
  aspectRatio: 1.3333333333333333,
  brightness: 0,
  colorTemperature: 4600,
  contrast: 0,
  deviceId: "3a505c29a3312600ea0afd79f8e2b4ba4fba3e539257801ff1de8718c27f2bed",
  exposureMode: "continuous",
  exposureTime: 156.25,
  focusDistance: 120,
  focusMode: "continuous",
  frameRate: 30,
  groupId: "35a82dcb7d5b0ef5bda550718d194f04a812c976175e926ccb81fb9d235d010f",
  height: 480,
  resizeMode: "none",
  saturation: 73,
  sharpness: 2,
  whiteBalanceMode: "continuous",
  width: 640
}
*/

See also

setFrameRate

Adjusts the frame rate.

Right now, this method only works in Chrome and should be called when the scanner is open.

setFrameRate(rate: number): Promise<void>

Parameters

rate : specifies the new frame rate.

Return value

A promise that resolves when the operation succeeds.

Code Snippet

await scanner.setFrameRate(10);

See also

setColorTemperature

Adjusts the color temperature.

Right now, this method only works in Chrome and should be called when the scanner is open.

setColorTemperature(colorTemperatur: number): Promise<void>

Parameters

colorTemperatur : specifies the new color temperature.

Return value

A promise that resolves when the operation succeeds.

Code Snippet

await scanner.setColorTemperature(5000);

See also

setExposureCompensation

Sets the exposure compensation index.

Right now, this method only works in Chrome and should be called when the scanner is open.

setExposureCompensation(exposureCompensation: number): Promise<void>

Parameters

exposureCompensation : specifies the new exposure compensation index.

Return value

A promise that resolves when the operation succeeds.

Code Snippet

await scanner.setExposureCompensation(-0.7);

See also

setZoom

Sets current zoom value.

setZoom(zoomValue: number): Promise<void>

Parameters

zoomValue : specifies the new zoom value.

Return value

A promise that resolves when the operation succeeds.

Code Snippet

await scanner.setZoom(400);

See also

turnOnTorch

Turns on the torch/flashlight.

Right now, this method only works in Chrome and should be called when the scanner is open.

turnOnTorch(): Promise<void>

Parameters

None.

Return value

A promise that resolves when the operation succeeds.

Code Snippet

await scanner.turnOnTorch();

See also

turnOffTorch

Turns off the torch/flashlight.

Right now, this method only works in Chrome and should be called when the scanner is open.

turnOffTorch(): Promise<void>

Parameters

None.

Return value

A promise that resolves when the operation succeeds.

Code Snippet

await scanner.turnOffTorch();

See also

This page is compatible for:

Version 7.5.0

Is this page helpful?

YesYes NoNo

In this article:

latest version

  • Latest version
  • Version 8.9.0
  • Version 8.8.7
  • Version 8.8.5
  • Version 8.8.3
  • Version 8.8.0
  • Version 8.6.3
  • Version 8.6.1
  • Version 8.6.0
  • Version 8.4.0
  • Version 8.2.5
  • Version 8.2.3
  • Version 8.2.1
  • Version 8.2.0
  • Version 8.1.3
  • Version 8.1.2
  • Version 8.1.0
  • Version 8.0.0
  • Version 7.6.0
  • Version 7.5.0
Change +
© 2003–2022 Dynamsoft. All rights reserved.
Privacy Statement / Site Map / Home / Purchase / Support