Dev Center
Table of contents

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.ui.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.onUniqueRead = 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
onUniqueRead This event is triggered when a new, unduplicated barcode is found.
onFrameRead This event is triggered after the library finishes scanning a frame.

Basic Interactions

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.
close() Stops decoding, releases camera and unbinds UI.

Scan Settings

API Name Description
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.
getFrameRate() Returns the real-time frame rate.
setColorTemperature() Adjusts the color temperature.
setExposureCompensation() Sets the exposure compensation index.
setFocus() Sets the focus mode and focus distance of the camera.
getFocus() Gets the focus mode and focus distance of the camera.
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

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>

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(): void

Code Snippet

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

isContextDestroyed

Returns whether the instance has been destroyed.

isContextDestroyed(): boolean

onUniqueRead

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.

onUniqueRead: (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.onUniqueRead = (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>

Return value

A promise resolving to a ScannerPlayCallbackInfo object.

Code Snippet

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

See also

hide

Stops decoding, releases camera and unbinds UI.

hide(): void

Return value

A promise that resolves when the operation succeeds.

Code Snippet

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

open

Binds UI, opens the camera and starts decoding.

open(): Promise<void>

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.

close(): void

Return value

A promise that resolves when the operation succeeds.

Code Snippet

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

pauseScan

Pauses the decoding process.

pauseScan(): void

resumeScan

Resumes the decoding process.

resumeScan(): void

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 (mobile only) or select an existing image for barcode reading.

Because the system camera of a mobile device can provide pictures with better quality, the API is useful when facing complex scenarios such as reading the dense PDF417 code on a driver license.

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

If the browser does not support the MediaDevices/getUserMedia API, the singleFrameMode will be set as true automatically when the API createInstance() is called.

singleFrameMode: boolean

Code Snippet

let scanner = await Dynamsoft.DBR.BarcodeScanner.createInstance();
if(didVideoStreamFailWhenReadingDriverLicenses){
  scanner.singleFrameMode = true;
  await scanner.show();
}

getScanSettings

Returns the current scan settings.

getScanSettings(): Promise<ScanSettings>

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 -->
<!-- The video element will be created and appended to the DIV element with the class dce-video-container , make sure the class name is the same.
Besides, the CSS property position of the DIV element must be either relative, absolute, fixed, or sticky. -->
<div class="dce-video-container" style="position:relative;width:100%;height:500px;"></div>
<script>
    let scanner = await Dynamsoft.DBR.BarcodeScanner.createInstance();
    await scanner.setUIElement(document.getElementsByClassName("dce-video-container")[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@9.0.0/dist/dbr.ui.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@9.0.0/dist/dbr.ui.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[]>

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>

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[]

Return value

An array of two numbers representing the resolution.

Code Snippet

let rsl = scanner.getResolution();
console.log(rsl[0] + " x " + rsl[1]);

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

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>

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

stop

Stops the video and releases the camera.

stop(): void

getCapabilities

Inspects and returns the capabilities of the current camera.

At present, this method only works in Edge, Safari, Chrome and other Chromium-based browsers (Firefox is not supported). Also, it should be called when a camera is open.

getCapabilities(): MediaTrackCapabilities

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},
  zoom: {max: 800, min: 100, step: 100},
}
*/

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

Return value

The current values for each constrainable property of the current camera in the form of a MediaTrackSettings object.

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,
  zoom: 100,
}
*/

See also

setFrameRate

Adjusts the frame rate.

At present, this method only works in Edge, Safari, Chrome and other Chromium-based browsers (Firefox is not supported). Also, it should be called when a camera 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

getFrameRate

Returns the real-time frame rate.

getFrameRate(): number;

Parameters

None.

Return value

The calculated real-time frame rate.

Code Snippet

await scanner.getFrameRate();

setColorTemperature

Adjusts the color temperature.

At present, this method only works in Edge, Chrome and other Chromium-based browsers (Firefox is not supported). Also, it should be called when a camera 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.

At present, this method only works in Edge, Chrome and other Chromium-based browsers (Firefox is not supported). Also, it should be called when a camera 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

setFocus

Sets the focus mode and focus distance of the camera.

At present, this method only works in Edge, Chrome and other Chromium-based browsers (Firefox is not supported). Also, it should be called when a camera is open.

setFocus(mode: string, distance?: number): Promise<void>;

Parameters

mode : specifies the focus mode, the available values include continuous and manual . distance : specifies the focus distance, only required when the mode is set to manual . Use getCapabilities to get the allowed value range.

Return value

A promise that resolves when the operation succeeds.

Code Snippet

await scanner.setFocus("manual", 400);

See also

getFocus

Gets the focus mode and the focus distance.

getFocus(): {mode: string, distance?: number};

Parameters

None.

Return value

A promise that resolves when the operation succeeds.

Code Snippet

await scanner.getFocus();

See also

setZoom

Sets current zoom value.

At present, this method only works in Edge, Chrome and other Chromium-based browsers (Firefox is not supported). Also, it should be called when a camera is open.

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 if the current camera supports it.

This method should be called when the camera is turned on. Note that it only works with Chromium-based browsers such as Edge and Chrome on Windows or Android. Other browsers such as Firefox or Safari are not supported. Note that all browsers on iOS (including Chrome) use WebKit as the rendering engine and are not supported.

turnOnTorch(): Promise<void>

Return value

A promise that resolves when the operation succeeds.

Code Snippet

await scanner.turnOnTorch();

See also

turnOffTorch

Turns off the torch/flashlight.

At present, this method only works in Edge, Chrome and other Chromium-based browsers (Firefox is not supported). Also, it should be called when a camera is open.

turnOffTorch(): Promise<void>

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:

version 9.0.0

  • Latest version(10.0.21)
  • Version 10.x
    • Version 10.0.20
  • Version 9.x
    • Version 9.6.40
    • Version 9.6.33
    • Version 9.6.32
    • Version 9.6.31
    • Version 9.6.30
    • Version 9.6.21
    • Version 9.6.20
    • Version 9.6.11
    • Version 9.6.10
    • Version 9.6.2
    • Version 9.6.1
    • Version 9.6.0
    • Version 9.3.1
    • Version 9.3.0
    • Version 9.2.13
    • Version 9.2.12
    • Version 9.2.11
    • Version 9.0.2
    • Version 9.0.1
    • Version 9.0.0
  • Version 8.x
    • Version 8.8.7
    • Version 8.8.5
    • Version 8.8.3
    • Version 8.8.0
    • Version 8.6.3
    • 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.x
    • Version 7.6.0
    • Version 7.5.0
Change +