From a089ab862d37c669ab65dcdac6070eaa34c82f58 Mon Sep 17 00:00:00 2001 From: DMGithubPublisher Date: Wed, 3 Sep 2025 09:38:02 +0800 Subject: [PATCH 1/3] update to internal commit 5c452f35 --- programming/javascript/samples-demos/index.md | 100 +++++++++++++++--- .../javascript/user-guide/zip-guide.md | 33 +++--- 2 files changed, 100 insertions(+), 33 deletions(-) diff --git a/programming/javascript/samples-demos/index.md b/programming/javascript/samples-demos/index.md index 17a9e31f..018a728a 100644 --- a/programming/javascript/samples-demos/index.md +++ b/programming/javascript/samples-demos/index.md @@ -8,7 +8,7 @@ noTitleIndex: true needAutoGenerateSidebar: false --- diff --git a/programming-old/javascript/samples-demos/helloworld-minCode.md b/programming-old/javascript/samples-demos/helloworld-minCode.md deleted file mode 100644 index ce375f79..00000000 --- a/programming-old/javascript/samples-demos/helloworld-minCode.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -layout: default-layout -title: Minimal Code Sample - Dynamsoft Barcode Reader JavaScript Edition -description: Dynamsoft Barcode Reader JavaScript Edition - Minimal Code -keywords: javascript, js, barcode, vanilla -noTitleIndex: true -breadcrumbText: Minimal Code -permalink: /programming/javascript/samples-demos/helloworld-minCode.html ---- - -# JavaScript Hello World Sample - Minimal Code - -As explained in the user guide, it takes just a few lines of code to implement Dynamsoft Barcode Reader JavaScript SDK in a web page. Read more about [the simplest implementation](../user-guide/#hello-world---simplest-implementation). - -## Official Sample - -* Read Barcodes from Camera - Source Code diff --git a/programming-old/javascript/samples-demos/helloworld-nextjs.md b/programming-old/javascript/samples-demos/helloworld-nextjs.md deleted file mode 100644 index eeb9fc4d..00000000 --- a/programming-old/javascript/samples-demos/helloworld-nextjs.md +++ /dev/null @@ -1,369 +0,0 @@ ---- -layout: default-layout -title: NextJS Integration Sample - Dynamsoft Barcode Reader JavaScript Edition -description: Dynamsoft Barcode Reader JavaScript Edition - nextJS Integration -keywords: javascript, js, barcode, nextjs -noTitleIndex: true -breadcrumbText: Next.JS -permalink: /programming/javascript/samples-demos/helloworld-nextjs.html ---- - -# JavaScript Hello World Sample - Next.js - -[Next.js](https://nextjs.org/) is an open-source development framework built on top of Node.js enabling [React](https://reactjs.org/) based web applications functionalities such as server-side rendering and generating static websites. Follow this guide to learn how to implement Dynamsoft Barcode Reader JavaScript SDK (hereafter called "the library") into a Next.js application. Note that in this sample we will use `TypeScript`. - -## Official Sample - -* Hello World in Next.js - Source Code - -## Preparation - -Make sure you have [node](https://nodejs.org/) installed. `node 14.21.3` and `next 13.2.4` are used in the example below. - -## Create the sample project - -### Create a Bootstrapped Raw Next.js Application - -```cmd -npx create-next-app@latest --typescript -``` - -### **CD** to the root directory of the application and install the dependencies - -```cmd -npm install dynamsoft-javascript-barcode -``` - -## Start to implement - -### Add a file dbr.ts at the root of the application to configure the library - -```jsx -import { BarcodeReader } from 'dynamsoft-javascript-barcode'; -BarcodeReader.license = 'DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9'; -BarcodeReader.engineResourcePath = "https://cdn.jsdelivr.net/npm/dynamsoft-javascript-barcode@9.6.42/dist/"; -``` - -> Note: -> * `license` specify a license key to use the library. You can visit [https://www.dynamsoft.com/customer/license/trialLicense?utm_source=sample&product=dbr&package=js](https://www.dynamsoft.com/customer/license/trialLicense?utm_source=sample&product=dbr&package=js) to get your own trial license good for 30 days. -> * `engineResourcePath` tells the library where to get the necessary resources at runtime. - -### Create a directory "components" and create the following files inside it to represent three components - -* VideoDecode.tsx -* ImgDecode.tsx -* HelloWorld.tsx - -### Edit the `VideoDecode` component - -* In VideoDecode.tsx, add code for initializing and destroying the `BarcodeScanner` instance. The `VideoDecode` component uses `BarcodeScanner` class of the library to help decode barcodes via camera. - -```tsx -import { BarcodeScanner } from "dynamsoft-javascript-barcode"; -import React from 'react'; -import styles from '@/styles/VideoDecode.module.css' - -class VideoDecode extends React.Component { - pScanner: Promise|null = null; - elRef: React.RefObject = React.createRef(); - async componentDidMount() { - try { - const scanner = await (this.pScanner = BarcodeScanner.createInstance()); - // Should judge if scanner is destroyed after 'await', as in development React runs setup and cleanup one extra time before the actual setup in Strict Mode. - if(scanner.isContextDestroyed()) return; - await scanner.setUIElement(this.elRef.current!); - // Should judge if scanner is destroyed after 'await', as in development React runs setup and cleanup one extra time before the actual setup in Strict Mode. - if(scanner.isContextDestroyed()) return; - scanner.onFrameRead = results => { - for (let result of results) { - console.log(result.barcodeText); - } - }; - scanner.onUniqueRead = (txt, result) => { - alert(txt); - } - await scanner.open(); - } catch (ex: any) { - if (ex.message.indexOf("network connection error")) { - let customMsg = "Failed to connect to Dynamsoft License Server: network connection error. Check your Internet connection or contact Dynamsoft Support (support@dynamsoft.com) to acquire an offline license."; - console.log(customMsg); - alert(customMsg); - } - throw ex; - } - } - async componentWillUnmount() { - if (this.pScanner) { - (await this.pScanner).destroyContext(); - console.log('BarcodeScanner Component Unmount'); - } - } - shouldComponentUpdate() { - // Never update UI after mount, dbrjs sdk use native way to bind event, update will remove it. - return false; - } - render() { - return ( -
- - -
-
-
-
-
- - -
-
- - - -
-
- ); - } -} - -export default VideoDecode; -``` - -> Note: -> * The html code in `render()` and the following code builds the UI for the library. -> -> ```jsx -> await scanner.setUIElement(this.elRef.current!); -> ``` -> -> * To release resources timely, the `BarcodeScanner` instance is destroyed with the component in the callback `componentWillUnmount`. -> * The component should never update (check the code for `shouldComponentUpdate()`) so that events bound to the UI stay valid. - -* Create 'VideoDecode.module.css' under '/styles/' and define the style of the component in it - -```css -.component-barcode-scanner{width:100%;height:100%;/* min-width:640px; */min-height:480px;background:#eee;position:relative;resize:both;} -.dce-bg-loading{display:none;animation:1s linear infinite dce-rotate;width:40%;height:40%;position:absolute;margin:auto;left:0;top:0;right:0;bottom:0;fill:#aaa;} -.dce-bg-camera{display:none;width:40%;height:40%;position:absolute;margin:auto;left:0;top:0;right:0;bottom:0;fill:#aaa;} -.dce-video-container{position:absolute;left:0;top:0;width:100%;height:100%;} -.dce-scanarea{width:100%;height:100%;position:absolute;left:0;top:0;} -.dce-scanlight{display:none;width:100%;height:3%;position:absolute;animation:3s infinite dce-scanlight;border-radius:50%;box-shadow:0px 0px 2vw 1px #00e5ff;background:#fff;} -.div-select-container{position:absolute;left:0;top:0;} -.dce-sel-camera{display:block;} -.dce-sel-resolution{display:block;margin-top:5px;} -.dbr-msg-poweredby{position:absolute;left:50%;bottom:10%;transform:translateX(-50%);} -.dbr-msg-poweredby svg {height:max(3vmin,17px);fill:#FFFFFF;} -@keyframes dce-rotate{from{transform:rotate(0turn);}to{transform:rotate(1turn);}} -@keyframes dce-scanlight{from{top:0;}to{top:97%;}} -``` - -### Edit the `ImgDecode` component - -* In ImgDecode.tsx, add code for initializing and destroying the `BarcodeReader` instance. The `ImgDecode` component uses `BarcodeReader` class of the library to help decode barcodes in an image. - -```tsx -import React, { ChangeEvent, Component } from 'react' -import { BarcodeReader } from "dynamsoft-javascript-barcode"; -import styles from '@/styles/ImgDecode.module.css' - -export default class ImgDecode extends Component { - pReader: Promise = BarcodeReader.createInstance(); - - decodeImg = async (e: ChangeEvent) => { - try { - const reader = await this.pReader; - let results = await reader.decode(e.target.files![0]); - for (let result of results) { - alert(result.barcodeText); - } - if (!results.length) { alert('No barcode found'); } - } catch (ex: any) { - if (ex.message.indexOf("network connection error")) { - let customMsg = "Failed to connect to Dynamsoft License Server: network connection error. Check your Internet connection or contact Dynamsoft Support (support@dynamsoft.com) to acquire an offline license."; - console.log(customMsg); - alert(customMsg); - } - throw ex; - } - e.target.value = ''; - } - - async componentWillUnmount() { - if (this.pReader) { - (await this.pReader).destroyContext(); - console.log('ImgDecode Component Unmount'); - } - } - - render() { - return ( -
- ) - } -} -``` - -* Create 'ImgDecode.module.css' under '/styles/' and define the style of the component in it - -```css -.ImgDecode { - display: flex; - justify-content: center; - align-items: center; - border: 1px solid black -} -``` - -### Edit the HelloWorld component - -* Add `VideoDecode` and `ImgDecode` components in HelloWorld.tsx - -```tsx -import React from 'react'; -import VideoDecode from './VideoDecode'; -import ImgDecode from './ImgDecode'; -import "../dbr"; // import side effects. The license, engineResourcePath, so on. -import { BarcodeReader } from "dynamsoft-javascript-barcode"; -import styles from '@/styles/HelloWorld.module.css' - -interface isState { - bShowScanner: boolean, - bShowImgDecode: boolean -} - -class HelloWorld extends React.Component { - state = { - bShowScanner: true, - bShowImgDecode: false - }; - - async componentDidMount() { - try { - await BarcodeReader.loadWasm(); - } catch (ex: any) { - if (ex.message.indexOf("network connection error")) { - let customMsg = "Failed to connect to Dynamsoft License Server: network connection error. Check your Internet connection or contact Dynamsoft Support (support@dynamsoft.com) to acquire an offline license."; - console.log(customMsg); - alert(customMsg); - } - throw ex; - } - } - - showScanner = () => { - this.setState({ - bShowScanner: true, - bShowImgDecode: false - }); - } - - showImgDecode = () => { - this.setState({ - bShowScanner: false, - bShowImgDecode: true - }); - } - - render() { - return ( -
-

Hello World for Next.js

-
- - -
-
- {this.state.bShowScanner ? () : ""} - {this.state.bShowImgDecode ? () : ""} -
-
- ); - } -} -export default HelloWorld; -``` - -* Create 'HelloWorld.module.css' under '/styles/' and define the style of the component in it - -```css -.helloWorld { - display: flex; - flex-direction: column; - align-items: center; - justify-content: center; - width: 100%; - height: 100%; - color: #455A64; -} - -.header { - font-size: 1.5em; -} - -.button { - font-size: 1.5rem; - margin: 1.5vh 0; - border: 1px solid black; - background-color: white; - color: black; -} - -.container { - margin: 2vmin auto; - width: 100%; -} -``` - -### Add the HelloWorld component to /pages/index.tsx - -In index.tsx, import the `HelloWorld` component: - -```jsx -import HelloWorld from '../components/HelloWorld' -``` - -Change the <main> tag like this: - -```jsx -
-
- -
-
-``` - -* Define the style of the "App" element in styles/Home.module.css - -```css -.UIElement { - margin: 2vmin auto; - text-align: center; - font-size: medium; - width: 80vw; -} -``` - -* Try running the project. - -```cmd -npm run dev -``` - -If you have followed all the steps correctly, you should now have a functioning page that allows you to scan barcodes from a webcam or a built-in camera. Additionally, if you want to decode a local image, you can click the `Image Decode` button and select the image you want to decode. Any barcodes that are detected will be displayed in a dialog. - -## Project Setup - -```sh -npm install -``` - -### Compile and Hot-Reload for Development - -```sh -npm run dev -``` - -### Type-Check, Compile and Minify for Production - -```sh -npm run build -``` \ No newline at end of file diff --git a/programming-old/javascript/samples-demos/helloworld-nuxtjs.md b/programming-old/javascript/samples-demos/helloworld-nuxtjs.md deleted file mode 100644 index 775653ac..00000000 --- a/programming-old/javascript/samples-demos/helloworld-nuxtjs.md +++ /dev/null @@ -1,485 +0,0 @@ ---- -layout: default-layout -title: Nuxt Integration Sample - Dynamsoft Barcode Reader JavaScript Edition -description: Dynamsoft Barcode Reader JavaScript Edition - Nuxt Integration -keywords: javascript, js, barcode, nuxt -noTitleIndex: true -breadcrumbText: Nuxt -permalink: /programming/javascript/samples-demos/helloworld-nuxtjs.html ---- - -# JavaScript Hello World Sample - NuxtJS - -[Nuxt](https://nuxtjs.org/) is a higher-level framework that builds on top of [Vue](https://vuejs.org/). Check out the following guide on how to implement Dynamsoft Barcode Reader JavaScript SDK (hereafter called "the library") into a Nuxt application. Note that in this sample we will use `TypeScript`. - -## Official Sample - -* Hello World in Nuxt - Source Code - -## Preparation - -Make sure you have [node](https://nodejs.org/) installed. `node 14.21.3` and `nuxt 3.2.3` are used in this article. - -## Create the sample project - -### Create a Bootstrapped Nuxt Application - -```cmd -npx nuxi@latest init read-video-nuxtjs -``` - -You will be asked to configure quite a few things for the application during the creation. In our example, we chose the default one in every step. - -### **CD** to the root directory of the application and install the dependencies - -```cmd -cd read-video-nuxtjs -npm install dynamsoft-javascript-barcode -``` - -## Start to implement - -### Add a file "dbr.ts" at the root of the app to configure the library - -```typescript -import { BarcodeReader } from 'dynamsoft-javascript-barcode'; -BarcodeReader.license = 'DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9'; -BarcodeReader.engineResourcePath = "https://cdn.jsdelivr.net/npm/dynamsoft-javascript-barcode@9.6.42/dist/"; -``` - -> Note: -> -> * `license` specify a license key to use the library. You can visit [https://www.dynamsoft.com/customer/license/trialLicense?utm_source=sample&product=dbr&package=js](https://www.dynamsoft.com/customer/license/trialLicense?utm_source=sample&product=dbr&package=js) to get your own trial license good for 30 days. -> * `engineResourcePath` tells the library where to get the necessary resources at runtime. - -### Create a directory "components" and create the following files inside it to represent three components - -* VideoDecode.vue -* ImgDecode.vue -* HelloWorld.vue - -### Edit the `VideoDecode` component - -* Add a file `VideoDecode.vue` under "/components/" as the `VideoDecode` component. The `VideoDecode` component uses `BarcodeScanner` class of the library to help decode barcodes via camera. - -* In `VideoDecode.vue`, add code for initializing and destroying the `BarcodeScanner` instance. - -```vue - - - - - -``` - -> Note: -> -> * The element with class name "component-barcode-scanner" is used to build the UI for the library in this line -> -> ```typescript -> await scanner.setUIElement(elRefs.value); -> ``` -> -> * To release resources timely, the `BarcodeScanner` instance is destroyed with the component in the callback `onBeforeUnmount` . - -### Edit the `ImgDecode` component - -* Add a file `ImgDecode.vue` under "/components/" as the `ImgDecode` component. The `ImgDecode` component uses `BarcodeReader` class of the library to help decode barcodes in an image. - -* In `ImgDecode.vue`, add code for initializing and destroying the `BarcodeReader` instance. - -```vue - - - - - -``` - -### Add `VideoDecode` and `ImgDecode` components in `HelloWorld.vue` - -```vue - - - - - -``` - -> NOTE : -> -> * The method `loadWasm()` initializes the library in the background. - -### Add the `HelloWorld` component to `app.vue` - -Edit the file `App.vue` to be like this - -```vue - -``` - -* Try running the project. - -```cmd -npm run dev -``` - -If you have followed all the steps correctly, you should now have a functioning page that allows you to scan barcodes from a webcam or a built-in camera. Additionally, if you want to decode a local image, you can click the `Image Decode` button and select the image you want to decode. Any barcodes that are detected will be displayed in a dialog. - -## Project Setup - -```sh -npm install -``` - -### Compile and Hot-Reload for Development - -```sh -npm run dev -``` - -### Type-Check, Compile and Minify for Production - -```sh -npm run build -``` \ No newline at end of file diff --git a/programming-old/javascript/samples-demos/helloworld-pwa.md b/programming-old/javascript/samples-demos/helloworld-pwa.md deleted file mode 100644 index 6ebaf897..00000000 --- a/programming-old/javascript/samples-demos/helloworld-pwa.md +++ /dev/null @@ -1,213 +0,0 @@ ---- -layout: default-layout -title: PWA Sample - Dynamsoft Barcode Reader JavaScript Edition -description: Dynamsoft Barcode Reader JavaScript Edition - PWA -keywords: javascript, js, barcode, pwa -noTitleIndex: true -breadcrumbText: PWA -permalink: /programming/javascript/samples-demos/helloworld-pwa.html ---- - -# JavaScript Hello World Sample - PWA - -[PWA](https://web.dev/progressive-web-apps/) is short for Progressive Web Apps which stand for web applications that have been designed to behave like platform-specific (native) applications. Check out the following on how to implement Dynamsoft Barcode Reader JavaScript SDK (hereafter called "the library") into a PWA application. - -## Official Sample - -* Hello World in PWA - Source Code - -## Preparation - -We will try to turn our most basic hello world sample into a PWA. - -First, create a file with the name "helloworld-pwa.html" and fill it with the following code: - -```html - - - - - - - Dynamsoft Barcode Reader PWA Sample - Hello World (Decoding via Camera) - - - -

Hello World for PWA

- Loading... - - - - - -``` - -Next, set up a secure environment (HTTPs) to run the page "helloworld-pwa.html". This is required because PWAs only run in secure environments. - -In our case, we use IIS to set up a secure site at "https://localhost" and the page is put at the root so that it can be accessed at "https://localhost/helloworld-pwa.html". - -## Make the app progressive - -### Register a service worker for offline support - -As the basis for PWAs, Service Workers are a virtual proxy between the browser and the network. A service worker can serve content offline, handle notifications and perform heavy calculations, etc. all on a separate thread. - -To use a service worker, we first need to register it. In the helloworld-pwa.html file, add the following at the end of the script: - -```javascript -if ('serviceWorker' in navigator) { - navigator.serviceWorker.register('./service-worker.js'); -}; -``` - -Create the service-worker.js file with the following content: - -```javascript -// Files to cache -const cacheName = 'helloworld-pwa'; -const appShellFiles = [ - './helloworld-pwa.html', -]; - -// Installing Service Worker -self.addEventListener('install', (e) => { - console.log('[Service Worker] Install'); - e.waitUntil((async () => { - const cache = await caches.open(cacheName); - console.log('[Service Worker] Caching all: app shell and content'); - await cache.addAll(appShellFiles); - })()); -}); - -self.addEventListener('fetch', (e) => { - e.respondWith((async () => { - const r = await caches.match(e.request); - console.log(`[Service Worker] Fetching resource: ${e.request.url}`); - if (r) { return r; } - const response = await fetch(e.request); - const cache = await caches.open(cacheName); - console.log(`[Service Worker] Caching new resource: ${e.request.url}`); - if (e.request.method !== "POST") - cache.put(e.request, response.clone()); - return response; - })()); -}); -``` - -With the above code, the application can now work offline because the service worker will cache the page helloworld-pwa.html and its related resources. - -For more information, refer to [Making PWAs work offline with Service workers](https://developer.mozilla.org/en-US/docs/Web/Progressive_web_apps/Offline_Service_workers). - -> NOTE -> -> Since the files are being cached, changes we make in later steps may not be reflected. Therefore, don't forget to clear the cache after a change is made. To do so, you can run the following in the browser console. -> -> ```javascript -> const cacheName = 'helloworld-pwa'; -> const cache = await caches.delete(cacheName); -> ``` - -### Use a web manifest file to make the application installable - -A web manifest file contains a list of information about a website in a JSON format. This information is used to present the web app correctly for installation on a device. - -In our example, we first create a file "helloworld-pwa.webmanifest" with the following content: - -```json -{ - "name": "Dynamsoft Barcode Reader Progressive Web App", - "short_name": "DBR-PWA", - "description": "Progressive Web App that reads barcodes from a video input with Dynamsoft Barcode Reader.", - "start_url": "./helloworld-pwa.html", - "scope": ".", - "display": "standalone", - "theme_color": "#B12A34", - "background_color": "#B12A34", - "icons": [ - { - "src": "./dynamsoft-512x512.png", - "sizes": "512x512", - "type": "image/png" - }, - { - "src": "./dynamsoft-192x192.png", - "sizes": "192x192", - "type": "image/png" - } - ] -} -``` - -> The icon files can be found in the github repository. - -Then we include the file in the <head> block of the helloworld-pwa.html file: - -```html - -``` - -For compatibility on safari, we need add some `meta` in ``: - -```html - - - - - - - -``` - -Now, if you open the application again in your browser, you will notice an install icon appear on the right side of the address bar. When you click on it, a pop-up will appear asking if you want to install the app. - -Once installed, you can use it like a native app. - -For offline use, you need to cache more files. - -service-worker.js -```javascript -const dbrVersion = "9.6.11"; -const dbrCdn = `https://cdn.jsdelivr.net/npm/dynamsoft-javascript-barcode@${dbrVersion}/dist/`; - -const appShellFiles = [ - './helloworld-pwa.html', - './dynamsoft-192x192.png', - './dynamsoft-512x512.png', - './helloworld-pwa.json', - `${dbrCdn}dbr.js`, - `${dbrCdn}dbr-${dbrVersion}.full.wasm`, - `${dbrCdn}dbr-${dbrVersion}.full.wasm.js`, - `${dbrCdn}dbr-${dbrVersion}.browser.worker.js`, -]; -``` - -## Summary - -In this article we took a look at how you can turn a simple barcode reading page into a PWA that is installable, re-engageable and capable of working offline. To learn more about Progressive web apps, you can click [here](https://developer.mozilla.org/en-US/docs/Web/Progressive_web_apps). \ No newline at end of file diff --git a/programming-old/javascript/samples-demos/helloworld-reactjs.md b/programming-old/javascript/samples-demos/helloworld-reactjs.md deleted file mode 100644 index 0c3504e9..00000000 --- a/programming-old/javascript/samples-demos/helloworld-reactjs.md +++ /dev/null @@ -1,377 +0,0 @@ ---- -layout: default-layout -title: ReactJS Integration Sample - Dynamsoft Barcode Reader JavaScript Edition -description: Dynamsoft Barcode Reader JavaScript Edition - ReactJS Integration -keywords: javascript, js, barcode, reactjs -noTitleIndex: true -breadcrumbText: React -permalink: /programming/javascript/samples-demos/helloworld-reactjs.html ---- - -# JavaScript Hello World Sample - React - -[React](https://reactjs.org/) is a JavaScript library meant explicitly for creating interactive UIs. Follow this guide to learn how to implement Dynamsoft Barcode Reader JavaScript SDK (hereafter called "the library") into a React application. Note that in this sample we will use `TypeScript` and define components as classes. Also, there is another sample `read-video-react-hooks` showing using `Hooks` in React. - -## Official Sample - -* Hello World in React - Source Code - -## Preparation - -Make sure you have [node](https://nodejs.org/) installed. `node 14.21.3` and `react 18.2.0` used in the example below. - -## Create the sample project - -### Create a Bootstrapped Raw React Application with TypeScript - -```cmd -npx create-react-app read-video-react --template typescript -``` - -### **CD** to the root directory of the application and install the library - -```cmd -cd read-video-react -npm install dynamsoft-javascript-barcode -``` - -## Start to implement - -### Add a file "dbr.ts" under "/src/" to configure the library - -```typescript -import { BarcodeReader } from 'dynamsoft-javascript-barcode'; -BarcodeReader.license = 'DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9'; -BarcodeReader.engineResourcePath = "https://cdn.jsdelivr.net/npm/dynamsoft-javascript-barcode@9.6.42/dist/"; -``` - -> Note: -> -> * `license` specify a license key to use the library. You can visit [https://www.dynamsoft.com/customer/license/trialLicense?utm_source=sample&product=dbr&package=js](https://www.dynamsoft.com/customer/license/trialLicense?utm_source=sample&product=dbr&package=js) to get your own trial license good for 30 days. -> * `engineResourcePath` tells the library where to get the necessary resources at runtime. - -### Build directory structure - -* Create a directory "components" under "/src/", and then create another three directories "HelloWorld", "VideoDecode" and "ImgDecode" under "/src/components/". - -### Create and edit the `VideoDecode` component - -* Create `VideoDecode.tsx` and `VideoDecode.css` under "/src/components/VideoDecode/". The `VideoDecode` component uses `BarcodeScanner` class of the library to decode barcodes via camera. - -* In `VideoDecode.tsx`, add code for initializing and destroying the `BarcodeScanner` instance. - -```tsx -import { BarcodeScanner } from "dynamsoft-javascript-barcode"; -import React from 'react'; -import './VideoDecode.css' - -class VideoDecode extends React.Component { - pScanner: Promise|null = null; - elRef: React.RefObject = React.createRef(); - async componentDidMount() { - try { - const scanner = await (this.pScanner = BarcodeScanner.createInstance()); - // Should judge if scanner is destroyed after 'await', as in development React runs setup and cleanup one extra time before the actual setup in Strict Mode. - if(scanner.isContextDestroyed()) return; - await scanner.setUIElement(this.elRef.current!); - // Should judge if scanner is destroyed after 'await', as in development React runs setup and cleanup one extra time before the actual setup in Strict Mode. - if(scanner.isContextDestroyed()) return; - scanner.onFrameRead = results => { - for (let result of results) { - console.log(result.barcodeText); - } - }; - scanner.onUniqueRead = (txt, result) => { - alert(txt); - } - await scanner.open(); - } catch (ex: any) { - if (ex.message.indexOf("network connection error")) { - let customMsg = "Failed to connect to Dynamsoft License Server: network connection error. Check your Internet connection or contact Dynamsoft Support (support@dynamsoft.com) to acquire an offline license."; - console.log(customMsg); - alert(customMsg); - } - throw ex; - } - } - async componentWillUnmount() { - if (this.pScanner) { - (await this.pScanner).destroyContext(); - console.log('BarcodeScanner Component Unmount'); - } - } - shouldComponentUpdate() { - // Never update UI after mount, dbrjs sdk use native way to bind event, update will remove it. - return false; - } - render() { - return ( -
- - -
-
-
-
-
- - -
-
- - - -
-
- ); - } -} - -export default VideoDecode; -``` - -> Note: -> -> * The html code in `render()` and the following code builds the UI for the library. -> -> ```jsx -> await scanner.setUIElement(this.elRef.current!); -> ``` -> -> * The component should never update (check the code for `shouldComponentUpdate()`) so that events bound to the UI stay valid. - -* Define the style of the element in `VideoDecode.css` - -```css -.component-barcode-scanner{width:100%;height:100%;/* min-width:640px; */min-height:480px;background:#eee;position:relative;resize:both;} -.dce-bg-loading{display:none;animation:1s linear infinite dce-rotate;width:40%;height:40%;position:absolute;margin:auto;left:0;top:0;right:0;bottom:0;fill:#aaa;} -.dce-bg-camera{display:none;width:40%;height:40%;position:absolute;margin:auto;left:0;top:0;right:0;bottom:0;fill:#aaa;} -.dce-video-container{position:absolute;left:0;top:0;width:100%;height:100%;} -.dce-scanarea{width:100%;height:100%;position:absolute;left:0;top:0;} -.dce-scanlight{display:none;width:100%;height:3%;position:absolute;animation:3s infinite dce-scanlight;border-radius:50%;box-shadow:0px 0px 2vw 1px #00e5ff;background:#fff;} -.div-select-container{position:absolute;left:0;top:0;} -.dce-sel-camera{display:block;} -.dce-sel-resolution{display:block;margin-top:5px;} -.dbr-msg-poweredby{position:absolute;left:50%;bottom:10%;transform:translateX(-50%);} -.dbr-msg-poweredby svg {height:max(3vmin,17px);fill:#FFFFFF;} -@keyframes dce-rotate{from{transform:rotate(0turn);}to{transform:rotate(1turn);}} -@keyframes dce-scanlight{from{top:0;}to{top:97%;}} -``` - -### Create and edit the `ImgDecode` component - -* Create `ImgDecode.tsx` and `ImgDecode.css` under "/src/components/ImgDecode/". The `ImgDecode` component uses `BarcodeReader` class of the library to help decode barcodes in an image. - -* In `ImgDecode.tsx`, add code for initializing and destroying the `BarcodeReader` instance. - -```tsx -import React, { ChangeEvent, Component } from 'react' -import { BarcodeReader } from "dynamsoft-javascript-barcode"; -import './ImgDecode.css' - -export default class ImgDecode extends Component { - pReader: Promise = BarcodeReader.createInstance(); - - decodeImg = async (e: ChangeEvent) => { - try { - const reader = await this.pReader; - let results = await reader.decode(e.target.files![0]); - for (let result of results) { - alert(result.barcodeText); - } - if (!results.length) { alert('No barcode found'); } - } catch (ex: any) { - if (ex.message.indexOf("network connection error")) { - let customMsg = "Failed to connect to Dynamsoft License Server: network connection error. Check your Internet connection or contact Dynamsoft Support (support@dynamsoft.com) to acquire an offline license."; - console.log(customMsg); - alert(customMsg); - } - throw ex; - } - e.target.value = ''; - } - - async componentWillUnmount() { - if (this.pReader) { - (await this.pReader).destroyContext(); - console.log('ImgDecode Component Unmount'); - } - } - - render() { - return ( -
- ) - } -} -``` - -* Define the style of the element in `ImgDecode.css` - -```css -.ImgDecode { - display: flex; - justify-content: center; - align-items: center; - border: 1px solid black -} -``` - -### Create and edit the HelloWorld component - -* Create `HelloWorld.tsx` and `HelloWorld.css` under "/src/components/HelloWorld/". The `HelloWorld` component offers buttons to switch components between `VideoDecode` and `ImgDecode`; - -* Add following code to `HelloWorld.tsx`. - -```tsx -import './HelloWorld.css'; -import reactLogo from '../../logo.svg'; -import "../../dbr"; // import side effects. The license, engineResourcePath, so on. -import { BarcodeReader } from "dynamsoft-javascript-barcode"; -import React from 'react'; -import VideoDecode from '../VideoDecode/VideoDecode'; -import ImgDecode from '../ImgDecode/ImgDecode'; - -interface isState { - bShowScanner: boolean, - bShowImgDecode: boolean -} - -class HelloWorld extends React.Component { - state = { - bShowScanner: true, - bShowImgDecode: false - }; - - async componentDidMount() { - try { - await BarcodeReader.loadWasm(); - } catch (ex: any) { - if (ex.message.indexOf("network connection error")) { - let customMsg = "Failed to connect to Dynamsoft License Server: network connection error. Check your Internet connection or contact Dynamsoft Support (support@dynamsoft.com) to acquire an offline license."; - console.log(customMsg); - alert(customMsg); - } - throw ex; - } - } - - showScanner = () => { - this.setState({ - bShowScanner: true, - bShowImgDecode: false - }); - } - - showImgDecode = () => { - this.setState({ - bShowScanner: false, - bShowImgDecode: true - }); - } - - render() { - return ( -
-

Hello World for Reactlogo

-
- - -
-
- {this.state.bShowScanner ? () : ""} - {this.state.bShowImgDecode ? () : ""} -
-
- ); - } -} -export default HelloWorld; -``` - -> NOTE : -> -> * The method `loadWasm()` initializes the library in the background. - -* Define the style of the element in `HelloWorld.css` - -```css -.helloWorld { - display: flex; - flex-direction: column; - align-items: center; - justify-content: center; - width: 100%; - height: 100%; - color: #455A64; -} - -h1 { - font-size: 1.5em; -} - -button { - font-size: 1.5rem; - margin: 1.5vh 0; - border: 1px solid black; - background-color: white; - color: black; -} - -.container { - margin: 2vmin auto; - text-align: center; - font-size: medium; - width: 80vw; -} -``` - -### Add the `HelloWorld` component to `App.tsx` - -Edit the file `App.tsx` to be like this - -```jsx -import React from 'react'; -import './App.css'; -import HelloWorld from './components/HelloWorld/HelloWorld'; - -function App() { - return ( -
- -
- ); -} - -export default App; -``` - -* Try running the project. - -```cmd -npm start -``` - -If you have followed all the steps correctly, you should now have a functioning page that allows you to scan barcodes from a webcam or a built-in camera. Additionally, if you want to decode a local image, you can click the `Image Decode` button and select the image you want to decode. Any barcodes that are detected will be displayed in a dialog. - -## Development server - -Runs the app in the development mode.\ -Open "http://localhost:3000" to view it in the browser. - -The page will reload if you make edits.\ -You will also see any lint errors in the console. - -## Build - -Builds the app for production to the `build` folder.\ -It correctly bundles React in production mode and optimizes the build for the best performance. - -The build is minified and the filenames include the hashes.\ -Your app is ready to be deployed! - -See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. - -## Support - -If you have any questions, feel free to contact Dynamsoft support via [email](mailto:support@dynamsoft.com) or live chat via the "Chat" button. \ No newline at end of file diff --git a/programming-old/javascript/samples-demos/helloworld-readFile.md b/programming-old/javascript/samples-demos/helloworld-readFile.md deleted file mode 100644 index 03b86a92..00000000 --- a/programming-old/javascript/samples-demos/helloworld-readFile.md +++ /dev/null @@ -1,95 +0,0 @@ ---- -layout: default-layout -title: Read An Image Sample - Dynamsoft Barcode Reader JavaScript Edition -description: Dynamsoft Barcode Reader JavaScript Edition - Read An Image -keywords: javascript, js, barcode, vanilla, image -noTitleIndex: true -breadcrumbText: Read An Image -permalink: /programming/javascript/samples-demos/helloworld-readFile.html ---- - -# JavaScript Hello World Sample - Read An Image - -In most cases, users of Dynamsoft Barcode Reader JavaScript SDK (hereafter called "the library") reads barcodes from a video input. In this article, we will discuss an uncommon usage of the library: reading barcodes from existing images. - -## Official Sample - -* Read Barcodes from An Existing Image - Source Code - -## Preparation - -In this article, we'll make use of the library through the `jsDelivr` CDN. Make sure you can access this file "https://cdn.jsdelivr.net/npm/dynamsoft-javascript-barcode@9.6.42/dist/dbr.js". - -## Create the sample page - -* Create an empty web page and name it "read-an-image.html" with the following code: - -```html - - - - - - - Dynamsoft Barcode Reader Sample - Read an Image - - - - - - - -``` - -* Add reference to the library in the page "head". - -```html - -``` - -* In the page "body", add an input for image selecting and a div for displaying the barcode results. - -```html - -
-``` - -* Add an event listner for the file input, then add barcode reading code in the callback. - -```javascript -let pReader = null; -Dynamsoft.DBR.BarcodeReader.license = 'DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9'; -document.getElementById('input-file').addEventListener('change', async function() { - try { - let resDIV = document.getElementById('results'); - let reader = await (pReader = pReader || Dynamsoft.DBR.BarcodeReader.createInstance()); - for (let i = 0; i < this.files.length; ++i) { - // Actually there will only be one file here (no 'multiple' attribute) - let file = this.files[i]; - // Decode the file - let results = await reader.decode(file); - if (results.length === 0) { - resDIV.innerHTML = "No Barcode Found!"; - return; - } - var info = ""; - for (let result of results) { - const format = result.barcodeFormat ? result.barcodeFormatString : result.barcodeFormatString_2; - info += "

" + format + ": " + result.barcodeText + "

"; - } - resDIV.innerHTML = info; - } - } catch (ex) { - alert(ex.message); - } -}); -``` - -> NOTE -> -> * An instance of the library is created when an image is selected for the first time. -> * The method `decode()` takes the file as the input, reads it and returns the results. - -In your application, the input may not be a file, the method `decode()` can handle the following types of input: `Blob`, `Buffer`, `ArrayBuffer`, `Uint8Array`, `Uint8ClampedArray`, `HTMLImageElement`, `HTMLCanvasElement`, `HTMLVideoElement`, `string`. - - diff --git a/programming-old/javascript/samples-demos/helloworld-requireJS.md b/programming-old/javascript/samples-demos/helloworld-requireJS.md deleted file mode 100644 index 5b3caf67..00000000 --- a/programming-old/javascript/samples-demos/helloworld-requireJS.md +++ /dev/null @@ -1,64 +0,0 @@ ---- -layout: default-layout -title: RequireJS Sample - Dynamsoft Barcode Reader JavaScript Edition -description: Dynamsoft Barcode Reader JavaScript Edition using RequireJS -keywords: javascript, js, barcode, vanilla, requirejs -noTitleIndex: true -breadcrumbText: RequireJS -permalink: /programming/javascript/samples-demos/helloworld-requireJS.html ---- - -# JavaScript Hello World Sample - RequireJS - -[RequireJS](https://requirejs.org/) is a JavaScript file and module loader. In this article, we will take a look at how to use the Dynamsoft Barcode Reader JavaScript SDK (hereafter called "the library") with RequireJS as shown in the code: - -* Read Barcodes from Camera - RequireJS - Source Code - -## Create a simple page for barcode reading with RequireJS - -### Include RequireJS on the page - -The first step is to load "require.js" on the page: - -```html - -``` - -### Use RequireJS to load the library - -Once RequireJS is enalbed, we can use the API `requirejs` to load the library from a CDN: - -```javascript -requirejs(['https://cdn.jsdelivr.net/npm/dynamsoft-javascript-barcode@9.6.42/dist/dbr.js'], - function({ - BarcodeScanner - }) {}); -``` - -As shown above, the `requirejs` method loads the library and imports two key objects to be used in the context. We use `DBR` to set up the library and then use `BarcodeScanner` to read barcodes from a video input. - -```javascript -BarcodeScanner.license = 'DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9'; -BarcodeScanner.engineResourcePath = "https://cdn.jsdelivr.net/npm/dynamsoft-javascript-barcode@9.6.42/dist/"; -let pScanner = null; -document.getElementById('readBarcode').onclick = async function() { - try { - let scanner = await (pScanner = pScanner || BarcodeScanner.createInstance()); - scanner.onFrameRead = results => { - console.log("Barcodes on one frame:"); - for (let result of results) { - const format = result.barcodeFormat ? result.barcodeFormatString : result.barcodeFormatString_2; - console.log(format + ": " + result.barcodeText); - } - }; - scanner.onUniqueRead = (txt, result) => { - alert(txt); - console.log("Unique Code Found: " + result); - } - await scanner.show(); - } catch (ex) { - alert(ex.message); - throw ex; - } -}; -``` diff --git a/programming-old/javascript/samples-demos/helloworld-vuejs.md b/programming-old/javascript/samples-demos/helloworld-vuejs.md deleted file mode 100644 index 13237528..00000000 --- a/programming-old/javascript/samples-demos/helloworld-vuejs.md +++ /dev/null @@ -1,505 +0,0 @@ ---- -layout: default-layout -title: Vue 2 Integration Sample - Dynamsoft Barcode Reader JavaScript Edition -description: Dynamsoft Barcode Reader JavaScript Edition - Vue 2 Integration -keywords: javascript, js, barcode, vue2 -noTitleIndex: true -breadcrumbText: Vue 2 -permalink: /programming/javascript/samples-demos/helloworld-vuejs.html ---- - -# JavaScript Hello World Sample - Vue - -[Vue](https://vuejs.org/) is a progressive framework for building user interfaces. Check out the following guide on how to implement Dynamsoft Barcode Reader JavaScript SDK (hereafter called "the library") into a Vue 2 application. - -## Official Sample - -* Hello World in Vue - Source Code - -## Preparation - -Make sure you have [node](https://nodejs.org/) installed. `node 14.21.3` and `vue 2.7.7` are used in the example below. - -## Create the sample project - -### Create a Bootstrapped Raw Vue Application - -```cmd -npm create vue@2 -``` - -### **CD** to the root directory of the application and install the dependencies - -```cmd -npm install -npm install dynamsoft-javascript-barcode -``` - -## Start to implement - -### Add a file "dbr.js" under "/src/" to configure the library - -```typescript -import { BarcodeReader } from 'dynamsoft-javascript-barcode'; -BarcodeReader.license = 'DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9'; -BarcodeReader.engineResourcePath = "https://cdn.jsdelivr.net/npm/dynamsoft-javascript-barcode@9.6.42/dist/"; -``` - -> Note: -> -> * `license` specify a license key to use the library. You can visit [https://www.dynamsoft.com/customer/license/trialLicense?utm_source=sample&product=dbr&package=js](https://www.dynamsoft.com/customer/license/trialLicense?utm_source=sample&product=dbr&package=js) to get your own trial license good for 30 days. -> * `engineResourcePath` tells the library where to get the necessary resources at runtime. - -### Create and edit the `VideoDecode` component - -* Add a file `VideoDecode.vue` under "/components/" as the `VideoDecode` component. The `VideoDecode` component uses `BarcodeScanner` class of the library to help decode barcodes via camera. - -* In `VideoDecode.vue`, add code for initializing and destroying the `BarcodeScanner` instance. - -```vue - - - - - - -``` - -> Note: -> -> * The element with class name "component-barcode-scanner" is used to build the UI for the library in this line -> -> ```typescript -> await scanner.setUIElement(this.$el); -> ``` -> -> * To release resources timely, the `BarcodeScanner` instance is destroyed with the component in the callback `beforeDestroy` . - -### Create and edit the `ImgDecode` component - -* Add a file `ImgDecode.vue` under "/components/" as the `ImgDecode` component. The `ImgDecode` component uses `BarcodeReader` class of the library to help decode barcodes in an image. - -* In `ImgDecode.vue`, add code for initializing and destroying the `BarcodeReader` instance. - -```vue - - - - - -``` - -### Add `VideoDecode` and `ImgDecode` components in `HelloWorld.vue` - -```vue - - - - - - -``` - -> NOTE : -> -> * The method `loadWasm()` initializes the library in the background. - -### Add the `HelloWorld` component to `App.vue` - -Edit the file `App.vue` to be like this - -```vue - - - - - -``` - -* Try running the project. - -```cmd -npm run dev -``` - -If you followed all the steps correctly, you will have a working page that turns one of the cameras hooked to or built in your computer or mobile device into a barcode scanner. Also, if you want to decode a local image, just click the `Image Decode` button and select the image you want to decode. Once barcodes are found, the results will show in a dialog. - -## Project setup - -```sh -npm install -``` - -### Compile and Hot-Reload for Development - -```sh -npm run dev -``` - -### Compile and Minify for Production - -```sh -npm run build -``` \ No newline at end of file diff --git a/programming-old/javascript/samples-demos/helloworld-vuejsv3.md b/programming-old/javascript/samples-demos/helloworld-vuejsv3.md deleted file mode 100644 index 376eb046..00000000 --- a/programming-old/javascript/samples-demos/helloworld-vuejsv3.md +++ /dev/null @@ -1,483 +0,0 @@ ---- -layout: default-layout -title: Vue 3 Integration Sample - Dynamsoft Barcode Reader JavaScript Edition -description: Dynamsoft Barcode Reader JavaScript Edition - Vue 3 Integration -keywords: javascript, js, barcode, vue3 -noTitleIndex: true -breadcrumbText: Vue 3 -permalink: /programming/javascript/samples-demos/helloworld-vuejsv3.html ---- - -# JavaScript Hello World Sample - Vue 3 - -[Vue 3](https://v3.vuejs.org/) is version 3 of Vue which is a progressive framework for building user interfaces. Check out the following guide on how to implement Dynamsoft Barcode Reader JavaScript SDK (hereafter called "the library") into a Vue 3 application. Note that in this sample we will use `TypeScript`. - -## Official Sample - -* Hello World in Vue 3 - Source Code - -## Preparation - -Make sure you have [node](https://nodejs.org/) installed. `node 14.21.3` and `vue 3.2.47` are used in the example below. - -## Create the sample project - -### Create a Bootstrapped Raw Vue Application - -```cmd -npm create vue@3 -# When asked 'Add TypeScript?', select 'Yes'. -``` - -### **CD** to the root directory of the application and install the dependencies - -```cmd -npm install -npm install dynamsoft-javascript-barcode -``` - -## Start to implement - -### Add a file "dbr.ts" under "/src/" to configure the library - -```typescript -import { BarcodeReader } from 'dynamsoft-javascript-barcode'; -BarcodeReader.license = 'DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9'; -BarcodeReader.engineResourcePath = "https://cdn.jsdelivr.net/npm/dynamsoft-javascript-barcode@9.6.42/dist/"; -``` - -> Note: -> -> * `license` specify a license key to use the library. You can visit [https://www.dynamsoft.com/customer/license/trialLicense?utm_source=sample&product=dbr&package=js](https://www.dynamsoft.com/customer/license/trialLicense?utm_source=sample&product=dbr&package=js) to get your own trial license good for 30 days. -> * `engineResourcePath` tells the library where to get the necessary resources at runtime. - -### Create and edit the `VideoDecode` component - -* Add a file `VideoDecode.vue` under "/components/" as the `VideoDecode` component. The `VideoDecode` component uses `BarcodeScanner` class of the library to help decode barcodes via camera. - -* In `VideoDecode.vue`, add code for initializing and destroying the `BarcodeScanner` instance. - -```vue - - - - - -``` - -> Note: -> -> * The element with class name "component-barcode-scanner" is used to build the UI for the library in this line -> -> ```typescript -> await scanner.setUIElement(elRefs.value); -> ``` -> -> * To release resources timely, the `BarcodeScanner` instance is destroyed with the component in the callback `onBeforeUnmount` . - -### Create and edit the `ImgDecode` component - -* Add a file `ImgDecode.vue` under "/components/" as the `ImgDecode` component. The `ImgDecode` component uses `BarcodeReader` class of the library to help decode barcodes in an image. - -* In `ImgDecode.vue`, add code for initializing and destroying the `BarcodeReader` instance. - -```vue - - - - - -``` - -### Add `VideoDecode` and `ImgDecode` components in `HelloWorld.vue` - -```vue - - - - - -``` - -> NOTE : -> -> * The method `loadWasm()` initializes the library in the background. - -### Add the `HelloWorld` component to `App.vue` - -Edit the file `App.vue` to be like this - -```vue - - - - - -``` - -* Try running the project. - -```cmd -npm run dev -``` - -If you have followed all the steps correctly, you should now have a functioning page that allows you to scan barcodes from a webcam or a built-in camera. Additionally, if you want to decode a local image, you can click the `Image Decode` button and select the image you want to decode. Any barcodes that are detected will be displayed in a dialog. - -## Project Setup - -```sh -npm install -``` - -### Compile and Hot-Reload for Development - -```sh -npm run dev -``` - -### Type-Check, Compile and Minify for Production - -```sh -npm run build -``` \ No newline at end of file diff --git a/programming-old/javascript/samples-demos/index-v9.6.42.md b/programming-old/javascript/samples-demos/index-v9.6.42.md deleted file mode 100644 index adcc43c5..00000000 --- a/programming-old/javascript/samples-demos/index-v9.6.42.md +++ /dev/null @@ -1,212 +0,0 @@ ---- -layout: default-layout -title: Samples and Demos Index - Dynamsoft Barcode Reader JavaScript Edition -description: Refer these samples and demos for different frameworks such as Angular, React, NuxtJS, etc, of Dynamsoft Barcode Reader JavaScript Edition. -keywords: javascript, js -breadcrumbText: Samples and Demos -noTitleIndex: true -needAutoGenerateSidebar: false -permalink: /programming/javascript/samples-demos/index-v9.6.42.html ---- - - - diff --git a/programming-old/javascript/samples-demos/others-index.md b/programming-old/javascript/samples-demos/others-index.md deleted file mode 100644 index 9ba393fd..00000000 --- a/programming-old/javascript/samples-demos/others-index.md +++ /dev/null @@ -1,94 +0,0 @@ ---- -layout: default-layout -title: Other Samples Index - Dynamsoft Barcode Reader JavaScript Edition -description: This is the main page of Dynamsoft Barcode Reader JavaScript SDK. -keywords: javascript, js -noTitleIndex: true -breadcrumbText: JavaScript -needAutoGenerateSidebar: false -permalink: /programming/javascript/samples-demos/others-index.html ---- - -
- -
-

Other Samples - DBR JavaScript Edition

-
- -
- diff --git a/programming-old/javascript/samples-demos/parameter-settings.md b/programming-old/javascript/samples-demos/parameter-settings.md deleted file mode 100644 index ac2916d4..00000000 --- a/programming-old/javascript/samples-demos/parameter-settings.md +++ /dev/null @@ -1,162 +0,0 @@ ---- -layout: default-layout -title: Parameter Settings Samples - Dynamsoft Barcode Reader JavaScript Edition -description: Dynamsoft Barcode Reader JavaScript Edition - Parameter Settings -keywords: javascript, js, barcode, vanilla, parameter -noTitleIndex: true -breadcrumbText: Parameter Settings -permalink: /programming/javascript/samples-demos/parameter-settings.html ---- - -# JavaScript Parameter Settings Samples - -Dynamsoft Barcode Reader JavaScript SDK (hereafter called "the library") is built based on Dynamsoft's algorithm. The algorithm is very flexible and has many configurable parameters. In this article, we'll take a look at how the library makes use of these parameters. - -Please note that most of the styling is common across the samples in this sample set. To improve the readability, we grouped the styling all in one file, settings-css.css. Additionally, the samples also share the same scanner initialization code. For the sake of clarity, the initialization code was also grouped in the same JS file, initScanner.js, and referenced throughout the different samples in this set. - -## Specify the Barcode Types and Number of Barcodes Per Image - -In many scenarios, an application only needs to decode one or a few types of barcodes that are predetermined. In fact, the algorithm can operate more efficiently when it is aware of the number of barcodes expected on an image. The following code snippet demonstrates how to decode two QR codes from an image. - -```javascript -const settings = await scanner.getRuntimeSettings(); -settings.barcodeFormatIds = Dynamsoft.DBR.EnumBarcodeFormat.BF_QR_CODE; -settings.expectedBarcodesCount = 2; -await scanner.updateRuntimeSettings(settings); -``` - -The following official sample showcases the same features. - -* Specify Barcode Types and Count - Source Code - -## Set Localization and Binarization Modes - -Localization and binarization are two essential steps in the barcode reading process. - -* Localization Modes - -Localization modes specify how the algorithm localize a barcode. At present, 8 modes are available: "Connected Blocks", "Statistics", "Lines", "Scan Directly", "Statistics Marks", "Statistics Postal Code", "Center" and "OneD Fast Scan". More information can be found [here](https://www.dynamsoft.com/barcode-reader/parameters/reference/localization-modes.html?ver=latest). A barcode reading session will attempt all of the set modes. The session will end once either the predefined number of barcodes are found or all of the set modes have been completed. The following code shows how to set multiple modes. - -```javascript -const settings = await scanner.getRuntimeSettings(); -settings.localizationModes = [2, 16, 4, 8, 32, 64, 0, 0]; -await scanner.updateRuntimeSettings(settings); -``` - -Note that each mode is represented by a number. - -Read more on [How to use different localization modes](https://www.dynamsoft.com/barcode-reader/parameters/scenario-settings/how-to-set-localization-modes.html). - -* Binarization Modes - -Binarization modes specify how the algorithm binarizes a colored or gray image. Right now, there are only two modes available: "Local Block" and "Threshold". More information can be found [here](https://www.dynamsoft.com/barcode-reader/parameters/reference/binarization-modes.html?ver=latest). - -For each mode, there are a few arguments to fine-tune it for best performance. Read more on [How to configure the binarization parameters](https://www.dynamsoft.com/barcode-reader/parameters/scenario-settings/how-to-set-binarization-modes.html?ver=latest). - -The following official sample demonstrates how to set Localization and Binarization modes. - -* Localization and Binarization - Source Code - -## Set Deblur Modes and Scale-up Modes - -* Deblur Modes - -The barcode reader often needs to handle blurry images, setting the deblur modes will help the algorithm better process them. In the library, there are 7 available modes: "Direct Binarization", "Threshold_Binarization", "Gray_Equalization", "Smoothing", "Morphing", "Deep_Analysis" and "Sharpening". More information can be found [here](https://www.dynamsoft.com/barcode-reader/parameters/reference/deblur-modes.html?ver=latest). A barcode reading session will attempt all of the set modes. The session will end once either the predefined number of barcodes are found or all of the set modes have been completed. The following code shows how to set multiple deblur modes. - -```javascript -const settings = await scanner.getRuntimeSettings(); -settings.deblurModes = [1, 2, 4, 8, 0, 0, 0, 0, 0, 0]; -await scanner.updateRuntimeSettings(settings); -``` - -* Scale-up Modes - -In many cases, the barcodes appear very small on the image and makes it difficult to read. The scale-up modes can be used to enlarge such barcodes before reading them. In the library, there are 2 available modes: "Linear_Interpolation" and "Nearest_Neighbour_Interpolation". More information can be found [here](https://www.dynamsoft.com/barcode-reader/parameters/reference/scale-up-modes.html?ver=latest). - -For each mode, there are a few arguments to fine-tune it for best performance. Read more on [How to read barcodes with small module sizes](https://www.dynamsoft.com/barcode-reader/docs/core/programming/features/read-barcodes-with-small-module-size.html). - -The following official sample demonstrates how to set Deblur modes and Scale-up modes. - -* Deblur Modes and Scale-Up Modes - Source Code - -## Deformation-Resisting Modes and Barcode-Complement Modes - -* Deformation-Resisting Modes - -As the name suggests, deformation-resisting modes deal with deformed barcocdes. Read more on [How to deal with deformed barcodes](https://www.dynamsoft.com/barcode-reader/parameters/scenario-settings/resist-deformation.html?ver=latest). - -For now, there is only one available mode: "General". - -The following code enables deformation resisting. - -```javascript -const settings = await scanner.getRuntimeSettings(); -settings.furtherModes.deformationResistingModes = [2, 0, 0, 0, 0, 0, 0, 0]; -await scanner.updateRuntimeSettings(settings); -``` - -* Barcode-Complement Modes - -QR codes and Data Matrix codes can be picked up even if they are incomplete. Read more on [How to decode incomplete barcodes](https://www.dynamsoft.com/barcode-reader/parameters/scenario-settings/how-to-set-barcode-complememt-modes.html?ver=latest). - -The parameter for this case is called [ `BarcodeComplementMode` ](https://www.dynamsoft.com/barcode-reader/parameters/reference/barcode-complement-modes.html?ver=latest) which has only one available mode at present: "General". - -The following code enables incomplete barcode reading. - -```javascript -const settings = await scanner.getRuntimeSettings(); -settings.furtherModes.deformationResistingModes = [2, 0, 0, 0, 0, 0, 0, 0]; -await scanner.updateRuntimeSettings(settings); -``` - -The following official sample showcases deformation resisting and barcode complementing. - -* Deformation-Resisting Modes and Barcode-Complement Modes - Source Code - -## Define or Detect the Region of Interest - -When reading barcodes from a video input, the barcode normally takes up only a small portion of the video frame. If the barcode always appear around the same spot, we can configure the ROI (Region of Interest) to speed up the barcode reading process. There are two ways to do this. - -* Manually define the ROI - -If the ROI is predetermined in the use case, we can manually set the limit. For example, the following only reads 25% of the central area. - -```javascript -const settings = await scanner.getRuntimeSettings(); -settings.region.regionMeasuredByPercentage = 1; -settings.region.regionLeft = 25; -settings.region.regionTop = 25; -settings.region.regionRight = 75; -settings.region.regionBottom = 75; -await scanner.updateRuntimeSettings(settings); -``` - -* Automatically detect the ROI - -To let the algorithm detect the ROI automatically, we can set the parameter [ `RegionPredetectionModes` ](https://www.dynamsoft.com/barcode-reader/parameters/reference/region-predetection-modes.html?ver=latest) which has four available modes: "General", "General_RGB_Contrast", "General_Gray_Contrast" and "General_HSV_Contrast". - -For each mode, there are a few arguments to fine-tune it for best performance. Read more on [How To Use Region Predetection](https://www.dynamsoft.com/barcode-reader/parameters/scenario-settings/how-to-use-region-predetection.html?ver=latest). - -The following official sample showcases both ways to specify ROI. - -* Define or Detect the Region of Interest - Source Code - -## Dealing with Dense Barcodes - -Some barcodes are designed to hold a lot of information which makes them very dense. To read such barcodes, we need to do two things - -1. Use a high resolution -2. Use the built-in "dense" template - -```javascript -await scanner.setResolution(3840, 2160); -await scanner.updateRuntimeSettings("dense"); -``` - -The following official sample showcases the performance of picking up dense barcodes with specific settings. - -* Dealing with Dense Barcodes - Source Code - -## Support - -If you have any questions, feel free to contact Dynamsoft support via [email](mailto:support@dynamsoft.com) or [live chat](https://www.dynamsoft.com/barcode-reader/sdk-javascript/) via the "Let's Chat" button. \ No newline at end of file diff --git a/programming-old/javascript/samples-demos/ui-customization.md b/programming-old/javascript/samples-demos/ui-customization.md deleted file mode 100644 index f1de0897..00000000 --- a/programming-old/javascript/samples-demos/ui-customization.md +++ /dev/null @@ -1,117 +0,0 @@ ---- -layout: default-layout -title: UI Customization Samples - Dynamsoft Barcode Reader JavaScript Edition -description: Dynamsoft Barcode Reader JavaScript Edition - UI Customization -keywords: javascript, js, barcode, vanilla, ui -noTitleIndex: true -breadcrumbText: UI Customization -permalink: /programming/javascript/samples-demos/ui-customization.html ---- - -# JavaScript UI Customization Samples - -Dynamsoft Barcode Reader JavaScript SDK (hereafter called "the library") provides a built-in GUI to help developers build an interactive barcode reading interface. - -## Default GUI - -The following official sample demonstrates the default GUI built into the library. - -* Use the Default Camera UI - Source Code - -**GUI Elements** - -If you check the GUI on the demo page, you will find that it consists of the following elements - -* The video element that streams the video from a camera -* A laser beam moving vertically which indicates the working status of the library -* A dropdown box for selecting a camera -* A dropdown box for specifying the resolution for the selected camera -* A close button that closes the GUI when clicked - -There are a few other elements - -* Before the video starts streaming, there is a spinner that indicates the loading process -* When a barcode is found, the barcode is highlighted with an overlay -* If no camera is found on the device or camera access is denied on the page, the GUI will show a camera icon, which, when clicked, allows the user to select a local image or invoke the system camera interface - -## Hide Built-in Controllers - -The default UI of the BarcodeReader class includes several elements that may not match the style of your application. The following code snippet demonstrates how to remove the camera selector, resolution selector, and close button, as well as change the background color: - -```html -
- -
-
-
-
-``` - -```javascript -await scanner.setUIElement(document.getElementById('div-ui-container')); -``` - -Official sample: - -* Hide Built-in Controllers - Source Code - -## Use External Controllers - -Based on the previous sample, you can build your own UI elements to control the barcode scanning process. - -For example, the following code adds a camera selector - -```html - -``` - -```javascript -async function updateCameras() { - let cameras = await scanner.getAllCameras(); - let cameraList = document.getElementById('cameraList'); - cameraList.options.length = 0; - for (let camera of cameras) { - let opt = new Option(camera.label, camera.deviceId); - cameraList.options.add(opt); - } -} -document.getElementById('cameraList').onchange = async function() { - try { - await scanner.setCurrentCamera(document.getElementById('cameraList').value); - } catch (ex) { - alert('Play video failed: ' + (ex.message || ex)); - } -}; -``` - -For more related customization, check out the following official sample: - -* Use External Controllers - Source Code - -## Enlarge the Video Stream - -The library is usually used on mobile devices which have small screens. When scanning barcodes with the mobile camera, the video stream will be limited in the video element and may not be clear enough. Ideally, we should use the whole screen to play the video and find barcodes. - -The GUI is pure HTML. Thus modifying the size of the element is easy. The following code expands the element to fill the entire viewport: - -```javascript -document.getElementById('UIElement').style.height = '100vh'; -document.getElementById('UIElement').style.width = '100vw'; -document.getElementById('UIElement').style.position = 'absolute'; -``` - -Check out the following example code to see how you can expand the video stream to read a barcode and then restore it to its normal size: - -* Enlarge the Video Stream - Source Code - -## Customize the Default Ui - -Check out the following example code that demonstrates how to create a custom viewer that is vastly different from the default one. You can feel the possibilities of customization: - -* Customize the Default Ui - Source Code - -To learn more about UI customization, please refer to its corresponding [section](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/user-guide/?ver=latest#customize-the-ui-optional) in the user guide. - -## Support - -If you have any questions, feel free to contact Dynamsoft support via [email](mailto:support@dynamsoft.com) or [live chat](https://www.dynamsoft.com/barcode-reader/sdk-javascript/) via the "Let's Chat" button. diff --git a/programming-old/javascript/samples-demos/use-cases.md b/programming-old/javascript/samples-demos/use-cases.md deleted file mode 100644 index 98b05a77..00000000 --- a/programming-old/javascript/samples-demos/use-cases.md +++ /dev/null @@ -1,67 +0,0 @@ ---- -layout: default-layout -title: Use Case Samples - Dynamsoft Barcode Reader JavaScript Edition -description: Dynamsoft Barcode Reader JavaScript Edition - Use Cases -keywords: javascript, js, barcode, use-case -noTitleIndex: true -breadcrumbText: Use Cases -permalink: /programming/javascript/samples-demos/use-cases.html ---- - -# Use Case Samples -[]() -## Read Barcodes and Fill Form Fields - -It's difficult to type long text on mobile devices, but if that text is encoded in a barcode, we can use the sdk to read the barcode and automatically enter the text. - -The following code shows how to automatically invoke the sdk to read a barcode and fill in an input box. - -```html - -``` - -```javascript -let scanner = null; -Dynamsoft.DBR.BarcodeReader.license = 'DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9'; -(async function () { - document.getElementById("input-to-fill").addEventListener('click', async function () { - try { - scanner = scanner || await Dynamsoft.DBR.BarcodeScanner.createInstance(); - scanner.onUniqueRead = (txt, result) => { - this.value = result.barcodeText; - scanner.hide(); - }; - await scanner.show(); - } catch (ex) { - alert(ex.message); - throw ex; - } - }); -})(); -``` - -The following sample demonstrates how to utilize the SDK to fill out form fields. - -* Read Barcodes and Fill Form Fields - Source Code - -## Read the PDF417 Barcode on the Driver's License - -The PDF417 barcode on an AAMVA compatible driver's license contains a lot of information which is encoded following the DL/ID Card Design Standard. Together with a simple parse function, we can use the SDK to read and extract the information. - -The following official sample shows how to use the sdk to read and extract driver's license information. - -* Read the PDF417 Barcode on the Driver's License - Source Code - -Also see [Driver's License Scanner SDK for Mobile and Web](https://www.dynamsoft.com/use-cases/driver-license/). - -## Read barcodes via camera and highlight results with custom style - -When the SDK picks up a barcode in video stream, it will highlight them with built-in style automatically. But it is also possible to customize the highlight style freely using the method 'convertToClientCoordinates()'. - -The following official sample shows how to hightlight results with custom style. - -* Read barcodes via camera and highlight results with custom style - Source Code - -## Support - -If you have any questions, feel free to [contact Dynamsoft](https://www.dynamsoft.com/contact/). diff --git a/programming-old/javascript/samples-demos/usecase1-formfill.md b/programming-old/javascript/samples-demos/usecase1-formfill.md deleted file mode 100644 index 04639a45..00000000 --- a/programming-old/javascript/samples-demos/usecase1-formfill.md +++ /dev/null @@ -1,43 +0,0 @@ ---- -layout: default-layout -title: Fill a Form - Dynamsoft Barcode Reader JavaScript Edition -description: Fill a Form Use Cases of Dynamsoft Barcode Reader JavaScript Edition -keywords: javascript, js, barcode, use-case -noTitleIndex: true -breadcrumbText: Use Cases -permalink: /programming/javascript/samples-demos/usecase1-formfill.html ---- - -# Read Barcodes and Fill Form Fields - -It's difficult to type long text on mobile devices, but if that text is encoded in a barcode, we can use the sdk to read the barcode and automatically enter the text. - -The following code shows how to automatically invoke the sdk to read a barcode and fill an input box. - -```html - -``` - -```javascript -let scanner = null; -Dynamsoft.DBR.BarcodeReader.license = 'DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9'; -(async function () { - document.getElementById("input-to-fill").addEventListener('click', async function () { - try { - scanner = scanner || await Dynamsoft.DBR.BarcodeScanner.createInstance(); - scanner.onUniqueRead = (txt, result) => { - this.value = result.barcodeText; - scanner.hide(); - }; - await scanner.show(); - } catch (ex) { - alert(ex.message); - throw ex; - } - }); -})(); -``` - -The following official sample shows how to use the sdk to fill multiple fields for a form. - -* Read Barcodes and Fill Form Fields - Source Code diff --git a/programming-old/javascript/samples-demos/usecase2-pdf417DL.md b/programming-old/javascript/samples-demos/usecase2-pdf417DL.md deleted file mode 100644 index 48d5e6de..00000000 --- a/programming-old/javascript/samples-demos/usecase2-pdf417DL.md +++ /dev/null @@ -1,19 +0,0 @@ ---- -layout: default-layout -title: Read Driver License - Dynamsoft Barcode Reader JavaScript Edition -description: Read Driver License Use Cases of Dynamsoft Barcode Reader JavaScript Edition -keywords: javascript, js, barcode, use-case -noTitleIndex: true -breadcrumbText: Use Cases -permalink: /programming/javascript/samples-demos/usecase2-pdf417DL.html ---- - -# Read the PDF417 Barcode on the Driver's License - -The PDF417 barcode on an AAMVA compatible driver's license contains a lot of information which is encoded following the DL/ID Card Design Standard. Together with a simple parse function, we can use the sdk to read and get the information to be used in our workflow. - -The following official sample shows how to use the sdk to read a driver's license and extract its information. - -* Read the PDF417 Barcode on the Driver's License - Source Code - -Also see [Driver's License Scanner SDK for Mobile and Web](https://www.dynamsoft.com/use-cases/driver-license/). diff --git a/programming-old/javascript/samples-demos/usecases-index.md b/programming-old/javascript/samples-demos/usecases-index.md deleted file mode 100644 index 4890fa16..00000000 --- a/programming-old/javascript/samples-demos/usecases-index.md +++ /dev/null @@ -1,98 +0,0 @@ ---- -layout: default-layout -title: UseCases Samples Index - Dynamsoft Barcode Reader JavaScript Edition -description: This is the index page of Dynamsoft Barcode Reader JavaScript SDK Usecase samples. -keywords: javascript, js, use case -noTitleIndex: true -breadcrumbText: JavaScript -needAutoGenerateSidebar: false -permalink: /programming/javascript/samples-demos/usecases-index.html ---- - -
- -
-

Use Case Samples - DBR JavaScript Edition

-
- -
- diff --git a/programming-old/javascript/user-guide/advanced-customizations.md b/programming-old/javascript/user-guide/advanced-customizations.md deleted file mode 100644 index 1f2ca1fd..00000000 --- a/programming-old/javascript/user-guide/advanced-customizations.md +++ /dev/null @@ -1,64 +0,0 @@ ---- -layout: default-layout -title: Advanced Customizations - Dynamsoft Barcode Reader JavaScript Edition -description: This page shows how to customize advanced features of Dynamsoft Barcode Reader JavaScript SDK. -keywords: user guide, advanced customizations, debug, area, region, javascript, js -needAutoGenerateSidebar: true -permalink: /programming/javascript/user-guide/advanced-customizations.html ---- - -# Advanced Customizations - -## Debugging with Logs - -Include the following in your code to print internal logs in the console. - -```javascript -Dynamsoft.BarcodeReader._onLog = console.log; -``` - -## Read a specific area/region - -To speed up the scanning process, you can choose to scan only a specific area/region. - -```javascript -let settings = await scanner.getRuntimeSettings(); -/* - * The following code shrinks the decoding region by 25% on all sides - */ -settings.region.regionMeasuredByPercentage = 1; -settings.region.regionLeft = 25; -settings.region.regionTop = 25; -settings.region.regionRight = 75; -settings.region.regionBottom = 75; -await scanner.updateRuntimeSettings(settings); -``` -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/taykq592/) - -## Show found barcodes - -Try the following code to show found barcodes in `input` elements on the page. - -```javascript - - - -let iptIndex = 0; -let scanner = null; -(async()=>{ - scanner = await Dynamsoft.BarcodeScanner.createInstance(); - await scanner.setUIElement(document.getElementById('div-video-container')); - scanner.onFrameRead = results => {console.log(results);}; - scanner.onUnduplicatedRead = (txt)=>{ - document.getElementById('ipt-' + iptIndex).value = txt; - if(3 == ++iptIndex){ - scanner.onUnduplicatedRead = undefined; - // Hide the scanner if you only need to read these three barcodes - scanner.hide(); - } - }; - await scanner.show(); -})(); -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/tz9ngm2a/) diff --git a/programming-old/javascript/user-guide/advanced-usage-v8.4.0.md b/programming-old/javascript/user-guide/advanced-usage-v8.4.0.md deleted file mode 100644 index fa9b254c..00000000 --- a/programming-old/javascript/user-guide/advanced-usage-v8.4.0.md +++ /dev/null @@ -1,102 +0,0 @@ ---- -layout: default-layout -title: v8.4.0 Advanced Usage - Dynamsoft Barcode Reader JavaScript Edition -description: This page shows how to customize advanced features of Dynamsoft Barcode Reader JavaScript SDK in version 8.4.0. -keywords: user guide, advanced customizations, debug, area, region, javascript, js -needAutoGenerateSidebar: true -permalink: /programming/javascript/user-guide/advanced-usage-v8.4.0.html ---- - -# Advanced Usage - -## Read a specific area/region - -To speed up the scanning process, you can choose to scan only a specific area/region. - -```javascript -let settings = await scanner.getRuntimeSettings(); -/* - * The following code shrinks the decoding region by 25% on all sides - */ -settings.region.regionMeasuredByPercentage = 1; -settings.region.regionLeft = 25; -settings.region.regionTop = 25; -settings.region.regionRight = 75; -settings.region.regionBottom = 75; -await scanner.updateRuntimeSettings(settings); -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/taykq592/) - -## Show internal logs - -Include the following in your code to print internal logs in the console. - -```javascript -Dynamsoft.DBR.BarcodeReader._onLog = console.log; -``` - -## Set mode arguments - -To precisely control a mode, you can adjust its specific parameters. - -```javascript -let settings = await scanner.getRuntimeSettings(); - -/* - * The following code sets the sensitivity of the TextureDetectionModes to 9 - */ - -settings.furtherModes.textureDetectionModes = [ - Dynamsoft.DBR.EnumTextureDetectionMode.TDM_GENERAL_WIDTH_CONCENTRATION, 0, 0, 0, 0, 0, 0, 0 -]; - -await scanner.updateRuntimeSettings(settings); -// The 2nd parameter 0 specifies the first mode of TextureDetectionModes, which is "Dynamsoft.DBR.EnumTextureDetectionMode.TDM_GENERAL_WIDTH_CONCENTRATION" in this case. -await scanner.setModeArgument("TextureDetectionModes", 0, "Sensitivity", "9"); -``` - -## Display the intermediate result images or the original canvas - -The intermediate result images are created when `intermediateResultTypes` is set in `RuntimeSettings` . Then they can be returned with the method `getIntermediateResults()` . These images can be used to show and debug the barcode reading process. - -The original canvas ( `oriCanvas` ) means the actual canvas which holds the image to be passed to the barcode reader engine for decoding. - -> *NOTE* -> -> For efficiency, the library may utilize WebGL (Web Graphics Library) for preprocessing an image before passing it to the barcode reader engine. If WebGL is used, the image captured from the camera will not be rendered on the canvas, instead, it gets processed by WebGL first and then is passed to the barcode reader engine directly. In this case, there won't be an original canvas. Therefore, if `bSaveOriCanvas` is set to `true` for a `BarcodeReader` or `BarcodeScanenr` instance, the WebGL feature will be disabled for that instance. -> -> On the other hand, if WebGL is disabled and you try to get the intermediate result specified by `EnumIntermediateResultType.IRT_ORIGINAL_IMAGE` , it will be exactly the same image as you would get with `oriCanvas` . - -The following shows how to display these images on the page - -```html -
-
-``` - -```javascript -(async () => { - let scanner = await Dynamsoft.DBR.BarcodeScanner.createInstance(); - /* The default of `_bUseWebgl` is true which means the intermediate result for - IRT_ORIGINAL_IMAGE will be one that has been preprocessed by WebGL */ - scanner._bUseWebgl = false; - document.getElementById('scannerV').appendChild(scanner.getUIElement());; - await scanner.updateRuntimeSettings('balance'); - let rs = await scanner.getRuntimeSettings(); - rs.intermediateResultTypes = 1; - await scanner.updateRuntimeSettings(rs); - scanner.onUnduplicatedRead = async (txt, result) => { - try { - let cvss = await scanner.getIntermediateCanvas(); - for (let cvs of cvss) { - document.getElementById('cvses').appendChild(cvs); - } - scanner.destroy(); - } catch (ex) { - console.error(ex); - } - }; - await scanner.show(); -})(); -``` diff --git a/programming-old/javascript/user-guide/advanced-usage-v8.8.7.md b/programming-old/javascript/user-guide/advanced-usage-v8.8.7.md deleted file mode 100644 index 58986437..00000000 --- a/programming-old/javascript/user-guide/advanced-usage-v8.8.7.md +++ /dev/null @@ -1,122 +0,0 @@ ---- -layout: default-layout -title: v8.8.7 Advanced Usage - Dynamsoft Barcode Reader JavaScript Edition -description: This page shows how to customize advanced features of Dynamsoft Barcode Reader JavaScript SDK in version 8.8.7. -keywords: user guide, advanced customizations, debug, area, region, javascript, js -needAutoGenerateSidebar: true -permalink: /programming/javascript/user-guide/advanced-usage-v8.8.7.html ---- - -# Advanced Usage - -## Read a specific area/region - -To speed up the scanning process, you can choose to scan only a specific area/region. - -```javascript -let settings = await scanner.getRuntimeSettings(); -/* - * The following code shrinks the decoding region by 25% on all sides - */ -settings.region.regionMeasuredByPercentage = 1; -settings.region.regionLeft = 25; -settings.region.regionTop = 25; -settings.region.regionRight = 75; -settings.region.regionBottom = 75; -await scanner.updateRuntimeSettings(settings); -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/taykq592/) - -## Show internal logs - -Include the following in your code to print internal logs in the console. - -```javascript -Dynamsoft.DBR.BarcodeReader._onLog = console.log; -``` - -## Set mode arguments - -To precisely control a mode, you can adjust its specific parameters. - -```javascript -let settings = await scanner.getRuntimeSettings(); - -/* - * The following code sets the sensitivity of the TextureDetectionModes to 9 - */ - -settings.furtherModes.textureDetectionModes = [ - Dynamsoft.DBR.EnumTextureDetectionMode.TDM_GENERAL_WIDTH_CONCENTRATION, 0, 0, 0, 0, 0, 0, 0 -]; - -await scanner.updateRuntimeSettings(settings); -// The 2nd parameter 0 specifies the 0th mode of TextureDetectionModes, -// which is "Dynamsoft.DBR.EnumTextureDetectionMode.TDM_GENERAL_WIDTH_CONCENTRATION" in this case. -await scanner.setModeArgument("TextureDetectionModes", 0, "Sensitivity", "9"); -``` - -## Display the original canvas or the intermediate result canvas - -The original canvases are saved when setting `ifSaveOriginalImageInACanvas` to `true`. The method `getOriginalImageInACanvas()` returns a canvas which holds the image to be passed to the barcode reader engine for decoding. - -The intermediate result canvases are created when `intermediateResultTypes` is set to a value other than `IRT_NO_RESULT` . Then these intermediate result canvases can be returned with the method `getIntermediateCanvas()` to be used for showing and debugging the barcode reading process. - -> *NOTE* -> -> For efficiency, the library may utilize WebGL (Web Graphics Library) for preprocessing an image before passing it to the barcode reader engine. If WebGL is used, the image captured from the camera will not be rendered on the canvas, instead, it gets processed by WebGL first and then is passed to the barcode reader engine directly. In this case, there won't be an original canvas. -> -> Therefore, if `ifSaveOriginalImageInACanvas` is set to `true` for a `BarcodeScanenr` instance, the WebGL feature will be disabled for that instance. -> -> You can manually disable the WebGL feature by setting `_bUseWebgl` as `false`. If WebGL is disabled, when you try to get the intermediate result canvas (with `getIntermediateCanvas()`) specified by `EnumIntermediateResultType.IRT_ORIGINAL_IMAGE` , the canvas will be exactly the same image as you would get with `getOriginalImageInACanvas()` . - -The following shows how to display these images on the page - -```html -
-
-``` - -```javascript -// original canvas -(async () => { - let scanner = await Dynamsoft.DBR.BarcodeScanner.createInstance(); - document.getElementById('scannerV').appendChild(scanner.getUIElement()); - scanner.ifSaveOriginalImageInACanvas = true; - scanner.onUnduplicatedRead = async (txt, result) => { - try { - let cvs = scanner.getOriginalImageInACanvas(); - document.getElementById('cvses').appendChild(cvs); - scanner.destroyContext(); - } catch (ex) { - console.error(ex); - } - }; - await scanner.show(); -})(); -``` - -```javascript -// intermediate result canvas -(async () => { - let scanner = await Dynamsoft.DBR.BarcodeScanner.createInstance(); - // scanner._bUseWebgl = false; - document.getElementById('scannerV').appendChild(scanner.getUIElement()); - let rs = await scanner.getRuntimeSettings(); - rs.intermediateResultTypes = Dynamsoft.DBR.EnumIntermediateResultType.IRT_ORIGINAL_IMAGE; - await scanner.updateRuntimeSettings(rs); - scanner.onUnduplicatedRead = async (txt, result) => { - try { - let cvss = await scanner.getIntermediateCanvas(); - for (let cvs of cvss) { - document.getElementById('cvses').appendChild(cvs); - } - scanner.destroyContext(); - } catch (ex) { - console.error(ex); - } - }; - await scanner.show(); -})(); -``` diff --git a/programming-old/javascript/user-guide/advanced-usage.md b/programming-old/javascript/user-guide/advanced-usage.md deleted file mode 100644 index ba80da68..00000000 --- a/programming-old/javascript/user-guide/advanced-usage.md +++ /dev/null @@ -1,237 +0,0 @@ ---- -layout: default-layout -title: Advanced Usage - Dynamsoft Barcode Reader JavaScript Edition -description: This page shows how to use advanced features of Dynamsoft Barcode Reader JavaScript SDK. -keywords: user guide, advanced customizations, debug, area, region, javascript, js -needAutoGenerateSidebar: true -permalink: /programming/javascript/user-guide/advanced-usage.html ---- - -# Advanced Usage - -- [Advanced Usage](#advanced-usage) - - [Read a specific area/region](#read-a-specific-arearegion) - - [Always draw a square as the scan region](#always-draw-a-square-as-the-scan-region) - - [Account for newline characters in the barcode result](#account-for-newline-characters-in-the-barcode-result) - - [Show internal logs](#show-internal-logs) - - [Cut down power usage](#cut-down-power-usage) - - [Remove highlighting of unverified linear barcodes](#remove-highlighting-of-unverified-linear-barcodes) - - [Set mode arguments](#set-mode-arguments) - - [Display images in different stages of the reading process](#display-images-in-different-stages-of-the-reading-process) - - [Hosting the library](#hosting-the-library) - - [Step One: Deploy the dist folder](#step-one-deploy-the-dist-folder) - - [Step Two: Configure the Server](#step-two-configure-the-server) - - [Step Three: Include the library from the server](#step-three-include-the-library-from-the-server) - -## Read a specific area/region - -To speed up the scanning process, you can choose to scan only a specific area/region. - -```javascript -let settings = await scanner.getRuntimeSettings(); -/* - * The following code shrinks the decoding region by 25% on all sides - */ -settings.region.regionMeasuredByPercentage = 1; -settings.region.regionLeft = 25; -settings.region.regionTop = 25; -settings.region.regionRight = 75; -settings.region.regionBottom = 75; -await scanner.updateRuntimeSettings(settings); -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/taykq592/) - -## Always draw a square as the scan region - -When reading square barcodes such as QR codes, it will help to keep the scan region also a square, the following code does the trick - -```javascript -scanner.onPlayed = async info => { - let sideLen = Math.min(info.width,info.height)*0.4; - let precentW = Math.round(sideLen/info.width*100) - let precentH = Math.round(sideLen/info.height*100); - let rs = await scanner.getRuntimeSettings(); - rs.region.regionLeft = (100 - precentW) / 2; - rs.region.regionRight = (100 + precentW) / 2; - rs.region.regionTop = (100 - precentH) / 2; - rs.region.regionBottom = (100 + precentH) / 2; - rs.region.regionMeasuredByPercentage = 1; - await scanner.updateRuntimeSettings(rs); -} -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/srny764o/) - -## Account for newline characters in the barcode result - -When it comes to HTML, newline characters ( `\n` ) are not interpreted as they normally would. Therefore, if a barcode result contains a newline character, and you display the result in an modal dialogue box or some other text elements, then the newline character will probably be ignored. - -There are two ways in which you can resolve this: - -1. Wrap the element used to display the result in a `
` element.
-2. Manually replace each `\n` character in the result with `
` - -## Show internal logs - -Include the following in your code to print internal logs in the console. - -```javascript -Dynamsoft.DBR.BarcodeReader._onLog = console.log; -``` - -## Cut down power usage - -> Applicable to version 9.2.10+ - -BarcodeScanner is designed for best performance, which means once it starts scanning, it'll keep the CPU focused on barcode reading with no pause. As a result, it quickly drains the device battery and causes the device to overheat. To cut down power usage, we can configure two things: - -1. Pause the barcode reading when capturing the next video frame; -2. Explicitly pause the SDK altogether for a short period after each successful read. - -```js -const scanSettings = await scanner.getScanSettings(); -scanSettings.captureAndDecodeInParallel = false; // When set to false, the SDK will pause reading when capturing the next frame. Otherwise, the SDK will capture the next frame while reading the current frame, which means it never stops. -scanSettings.intervalTime = 1000; // Tells the SDK to pause for 1 second after reading a frame before capturing the next frame. -await scanner.updateScanSettings(scanSettings); -``` - -## Remove highlighting of unverified linear barcodes - -> Applicable to version 9.3.0+ - -When linear barcodes are found but not verified, they will be highlighted in the video feed, but in a lighter color. If you wish to highlight only the verified barcodes, you can use the following code: - -```js -scanner.barcodeFillStyleBeforeVerification = "transparent"; // default value: "rgba(248,252,0,0.2)" -scanner.barcodeStrokeStyleBeforeVerification = "transparent"; // default value: "transparent" -``` - -## Set mode arguments - -To precisely control a mode, you can adjust its specific parameters. - -```javascript -let settings = await scanner.getRuntimeSettings(); - -/* - * The following code sets the sensitivity of the TextureDetectionModes to 9 - */ - -settings.furtherModes.textureDetectionModes = [ - Dynamsoft.DBR.EnumTextureDetectionMode.TDM_GENERAL_WIDTH_CONCENTRATION, 0, 0, 0, 0, 0, 0, 0 -]; - -await scanner.updateRuntimeSettings(settings); -// The 2nd parameter 0 specifies the 0th mode of TextureDetectionModes, -// which is "Dynamsoft.DBR.EnumTextureDetectionMode.TDM_GENERAL_WIDTH_CONCENTRATION" in this case. -await scanner.setModeArgument("TextureDetectionModes", 0, "Sensitivity", "9"); -``` - -## Display images in different stages of the reading process - -The original canvases are saved when setting `ifSaveOriginalImageInACanvas` to `true`. The method `getOriginalImageInACanvas()` returns a canvas which holds the image to be passed to the barcode reader engine for decoding. - -The intermediate result canvases are created when `intermediateResultTypes` is set to a value other than `IRT_NO_RESULT` . Then these intermediate result canvases can be returned with the method `getIntermediateCanvas()` to be used for showing and debugging the barcode reading process. - -> *NOTE* -> -> For efficiency, the SDK may utilize WebGL (Web Graphics Library) for preprocessing an image before passing it to the barcode reader engine. If WebGL is used, the image captured from the camera will not be rendered on the canvas, instead, it gets processed by WebGL first and then is passed to the barcode reader engine directly. In this case, there won't be an original canvas. -> -> Therefore, if `ifSaveOriginalImageInACanvas` is set to `true` for a `BarcodeScanenr` instance, the WebGL feature will be disabled for that instance. -> -> You can manually disable the WebGL feature by setting `_bUseWebgl` as `false`. If WebGL is disabled, when you try to get the intermediate result canvas (with `getIntermediateCanvas()`) specified by `EnumIntermediateResultType.IRT_ORIGINAL_IMAGE` , the canvas will be exactly the same image as you would get with `getOriginalImageInACanvas()` . - -The following shows how to display these images on the page - -```html -
-
-``` - -```javascript -// original canvas -(async () => { - let scanner = await Dynamsoft.DBR.BarcodeScanner.createInstance(); - document.getElementById('scannerV').appendChild(scanner.getUIElement()); - scanner.ifSaveOriginalImageInACanvas = true; - scanner.onUniqueRead = async (txt, result) => { - try { - let cvs = scanner.getOriginalImageInACanvas(); - document.getElementById('cvses').appendChild(cvs); - scanner.destroyContext(); - } catch (ex) { - console.error(ex); - } - }; - await scanner.show(); -})(); -``` - -```javascript -// intermediate result canvas -(async () => { - let scanner = await Dynamsoft.DBR.BarcodeScanner.createInstance(); - document.getElementById('scannerV').appendChild(scanner.getUIElement()); - let rs = await scanner.getRuntimeSettings(); - rs.intermediateResultTypes = Dynamsoft.DBR.EnumIntermediateResultType.IRT_ORIGINAL_IMAGE; - await scanner.updateRuntimeSettings(rs); - scanner.onUniqueRead = async (txt, result) => { - try { - let cvss = await scanner.getIntermediateCanvas(); - for (let cvs of cvss) { - document.getElementById('cvses').appendChild(cvs); - } - scanner.destroyContext(); - } catch (ex) { - console.error(ex); - } - }; - await scanner.show(); -})(); -``` - -## Hosting the library - -### Step One: Deploy the dist folder - -Once you have downloaded the library, you can locate the "dist" directory and copy it to your server (usually as part of your website / web application). - -Some of the files in this directory: - -* `dbr.js` // The main library file -* `dbr.mjs` // For using the library as a module (` -``` - -Optionally, you may also need to [specify the location of the "engine" files](index.md#specify-the-location-of-the-engine-files). diff --git a/programming-old/javascript/user-guide/basic-customizations-v7.5.0.md b/programming-old/javascript/user-guide/basic-customizations-v7.5.0.md deleted file mode 100644 index f09e86a2..00000000 --- a/programming-old/javascript/user-guide/basic-customizations-v7.5.0.md +++ /dev/null @@ -1,184 +0,0 @@ ---- -layout: default-layout -title: v7.5.0 Basic Customizations - Dynamsoft Barcode Reader JavaScript Edition -description: This page shows how to customize basic features of Dynamsoft Barcode Reader JavaScript SDK. -keywords: user guide, basic customizations, initialize, javascript, js -needAutoGenerateSidebar: true -permalink: /programming/javascript/user-guide/basic-customizations-v7.5.0.html ---- - -# Basic Customizations - -## Initializing - -The library is based on the `WebAssembly` standard; therefore, **on first use**, it needs some time to download and compile the `wasm` files. After first use, the browser may cache the file. - -`Dynamsoft.BarcodeReader.loadWasm` is the API to start the initialization. - -```javascript -try{ - await Dynamsoft.BarcodeReader.loadWasm(); -}catch(ex){ - console.error(ex); -} -``` - -Other APIs like `Dynamsoft.BarcodeReader.createInstance` and `Dynamsoft.BarcodeScanner.createInstance` will also call `loadWasm` during initialization. The following demonstrates the most common usage. - -```javascript -let reader = null; -let scanner = null; -try{ - reader = await Dynamsoft.BarcodeReader.createInstance(); - scanner = await Dynamsoft.BarcodeScanner.createInstance(); -}catch(ex){ - console.error(ex); -} -``` - - **NOTE**: Including the library with a script tag doesn't automatically initialize the library. For better performance, you may want to call loadWasm to download and compile the wasm file in advance and create a reader or scanner instance later. - -Initialization consists of the following steps: - -**1. Download** - Download the necessary resources. Usually, we deploy the resources on CDN and set a long cache duration. If your web server is faster, you should put the resources on your own server instead of using the CDN. - -**2. Compile** - The `wasm` files are automatically compiled once downloaded. The compilation time varies among different devices & browsers. While it takes less than a second on latest phones or PCs, it may take longer on older devices. - -**3. Initialize** - The library needs to initialize every time the page loads. The initialization means creating an `BarcodeReader` or `BarcodeScanner` instance with specified settings. - - -## Configuring Scanner Settings - -When creating an instance of the `BarcodeScanner` object, there are several configuration options. The following code shows some of the most popular ones: - -```javascript -// set which camera and what resolution to use -await scanner.updateVideoSettings({ video: { width: 1280, height: 720, facingMode: "environment" } }); - -// use one of three built-in RuntimeSetting templates, 'speed' is recommended for decoding from a video stream -await scanner.updateRuntimeSettings("speed"); - -// make changes to the template. The code snippet below demonstrates how to specify which symbologies are enabled -let runtimeSettings = await scanner.getRuntimeSettings(); -runtimeSettings.barcodeFormatIds = Dynamsoft.EnumBarcodeFormat.BF_ONED | Dynamsoft.EnumBarcodeFormat.BF_QR_CODE; -await scanner.updateRuntimeSettings(runtimeSettings); - -// set up the scanner behavior -let scanSettings = await scanner.getScanSettings(); -// disregard duplicated results found in a specified time period -scanSettings.duplicateForgetTime = 20000; -// set a scan interval so the library may release the CPU from time to time -scanSettings.intervalTime = 300; -await scanner.updateScanSettings(scanSettings); -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/yfkcajxz/) - -As you can see in the code, there are three types of configurations: - -- `get/updateVideoSettings`: Configures the data source, i.e., the video stream. These settings include which camera to use, the resolution, etc. Learn more [here](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia#Syntax). - -- `get/updateRuntimeSettings`: Configures the decode engine. Find a full list of these settings and their corresponding descriptions [here](../api-reference/global-interfaces.md#runtimesettings). Try in [JSFiddle](https://jsfiddle.net/DynamsoftTeam/f24h8c1m/). - - e.g., - - ```javascript - await barcodeScanner.updateRuntimeSettings("speed"); - await barcodeScanner.updateRuntimeSettings("balance"); - await barcodeScanner.updateRuntimeSettings("coverage"); - let settings = await barcodeScanner.getRuntimeSettings(); - settings.localizationModes = [ - Dynamsoft.EnumLocalizationMode.LM_CONNECTED_BLOCKS, - Dynamsoft.EnumLocalizationMode.LM_SCAN_DIRECTLY, - Dynamsoft.EnumLocalizationMode.LM_LINES, 0, 0, 0, 0, 0]; - settings.deblurLevel = 2; - await barcodeScanner.updateRuntimeSettings(settings); - ``` - -- `get/updateScanSettings`: Configures the behavior of the scanner which includes `duplicateForgetTime`, `intervalTime` and `filter`, etc. - -## Customizing the UI - -The library provides a built-in UI for the `BarcodeScanner`object where the default scanner UI is defined in the file `dist/dbr.scanner.html`. There are 3 ways to customize it: - -1. Modify the file `dist/dbr.scanner.html` directly. This option is only possible when you deploy these files yourself instead of using the CDN. - -2. Copy the file `dist/dbr.scanner.html`, modify it and specify the new file as the default UI by its URL `Dynamsoft.BarcodeScanner.defaultUIElementURL = url`. Note: you must set `defaultUIElementURL` before you call `createInstance`. - -3. Build the UI into your own web page and call `scanner.setUIElement(HTMLElement)` to specify that element. - - -The following is an example of the 3rd option above. - -```html - - - -
- -
- - - - - -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/2jzeq1r6/) - -The element `div-video-container` is used as the UI this div contains the video element for showing the video stream. - - **NOTE**: The class name of the video element must be set to `dbrScanner-video`. - - ```html - - ``` - -### Cameras and Resolution Options - -Next, you can add the camera list and resolution list. - - If the class names match the default ones, `dbrScanner-sel-camera` and `dbrScanner-sel-resolution`, the library will automatically populate the lists and handle the camera/resolution switching automatically. - -```html - -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/nbj75vxu/) - -```html - -``` - 8 default resolutions are populated automatically. - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/25v08paf/) - -The following code shows how to display a custom set of resolution options. - -```html - -``` - - **Possible Issue**: Generally, you need to provide a resolution that the camera supports. However, in case a camera does not support the specified resolution, it usually uses the nearest supported resolution. As a result, the selected resolution may not be the actual resolution used. - - **Solution**: Add an option with the class name `dbrScanner-opt-gotResolution` (as shown above) which the library will then use to show the actual resolution being used. - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/tnfjks4q/) - diff --git a/programming-old/javascript/user-guide/basic-customizations-v7.6.0.md b/programming-old/javascript/user-guide/basic-customizations-v7.6.0.md deleted file mode 100644 index 4aa4ce9e..00000000 --- a/programming-old/javascript/user-guide/basic-customizations-v7.6.0.md +++ /dev/null @@ -1,184 +0,0 @@ ---- -layout: default-layout -title: v7.6.0 Basic Customizations - Dynamsoft Barcode Reader JavaScript Edition -description: This page shows how to customize basic features of Dynamsoft Barcode Reader JavaScript SDK. -keywords: user guide, basic customizations, initialize, javascript, js -needAutoGenerateSidebar: true -permalink: /programming/javascript/user-guide/basic-customizations-v7.6.0.html ---- - -# Basic Customizations - -## Initializing - -The library is based on the `WebAssembly` standard; therefore, **on first use**, it needs some time to download and compile the `wasm` files. After first use, the browser may cache the file. - -`Dynamsoft.BarcodeReader.loadWasm` is the API to start the initialization. - -```javascript -try{ - await Dynamsoft.BarcodeReader.loadWasm(); -}catch(ex){ - console.error(ex); -} -``` - -Other APIs like `Dynamsoft.BarcodeReader.createInstance` and `Dynamsoft.BarcodeScanner.createInstance` will also call `loadWasm` during initialization. The following demonstrates the most common usage. - -```javascript -let reader = null; -let scanner = null; -try{ - reader = await Dynamsoft.BarcodeReader.createInstance(); - scanner = await Dynamsoft.BarcodeScanner.createInstance(); -}catch(ex){ - console.error(ex); -} -``` - - **NOTE**: Including the library with a script tag doesn't automatically initialize the library. For better performance, you may want to call loadWasm to download and compile the wasm file in advance and create a reader or scanner instance later. - -Initialization consists of the following steps: - -**1. Download** - Download the necessary resources. Usually, we deploy the resources on CDN and set a long cache duration. If your web server is faster, you should put the resources on your own server instead of using the CDN. - -**2. Compile** - The `wasm` files are automatically compiled once downloaded. The compilation time varies among different devices & browsers. While it takes less than a second on latest phones or PCs, it may take longer on older devices. - -**3. Initialize** - The library needs to initialize every time the page loads. The initialization means creating an `BarcodeReader` or `BarcodeScanner` instance with specified settings. - - -## Configuring Scanner Settings - -When creating an instance of the `BarcodeScanner` object, there are several configuration options. The following code shows some of the most popular ones: - -```javascript -// set which camera and what resolution to use -await scanner.updateVideoSettings({ video: { width: 1280, height: 720, facingMode: "environment" } }); - -// use one of three built-in RuntimeSetting templates, 'speed' is recommended for decoding from a video stream -await scanner.updateRuntimeSettings("speed"); - -// make changes to the template. The code snippet below demonstrates how to specify which symbologies are enabled -let runtimeSettings = await scanner.getRuntimeSettings(); -runtimeSettings.barcodeFormatIds = Dynamsoft.EnumBarcodeFormat.BF_ONED | Dynamsoft.EnumBarcodeFormat.BF_QR_CODE; -await scanner.updateRuntimeSettings(runtimeSettings); - -// set up the scanner behavior -let scanSettings = await scanner.getScanSettings(); -// disregard duplicated results found in a specified time period -scanSettings.duplicateForgetTime = 20000; -// set a scan interval so the library may release the CPU from time to time -scanSettings.intervalTime = 300; -await scanner.updateScanSettings(scanSettings); -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/yfkcajxz/) - -As you can see in the code, there are three types of configurations: - -- `get/updateVideoSettings`: Configures the data source, i.e., the video stream. These settings include which camera to use, the resolution, etc. Learn more [here](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia#Syntax). - -- `get/updateRuntimeSettings`: Configures the decode engine. Find a full list of these settings and their corresponding descriptions [here](../api-reference/global-interfaces.md#runtimesettings). Try in [JSFiddle](https://jsfiddle.net/DynamsoftTeam/f24h8c1m/). - - e.g., - - ```javascript - await barcodeScanner.updateRuntimeSettings("speed"); - await barcodeScanner.updateRuntimeSettings("balance"); - await barcodeScanner.updateRuntimeSettings("coverage"); - let settings = await barcodeScanner.getRuntimeSettings(); - settings.localizationModes = [ - Dynamsoft.EnumLocalizationMode.LM_CONNECTED_BLOCKS, - Dynamsoft.EnumLocalizationMode.LM_SCAN_DIRECTLY, - Dynamsoft.EnumLocalizationMode.LM_LINES, 0, 0, 0, 0, 0]; - settings.deblurLevel = 2; - await barcodeScanner.updateRuntimeSettings(settings); - ``` - -- `get/updateScanSettings`: Configures the behavior of the scanner which includes `duplicateForgetTime`, `intervalTime` and `filter`, etc. - -## Customizing the UI - -The library provides a built-in UI for the `BarcodeScanner`object where the default scanner UI is defined in the file `dist/dbr.scanner.html`. There are 3 ways to customize it: - -1. Modify the file `dist/dbr.scanner.html` directly. This option is only possible when you deploy these files yourself instead of using the CDN. - -2. Copy the file `dist/dbr.scanner.html`, modify it and specify the new file as the default UI by its URL `Dynamsoft.BarcodeScanner.defaultUIElementURL = url`. Note: you must set `defaultUIElementURL` before you call `createInstance`. - -3. Build the UI into your own web page and call `scanner.setUIElement(HTMLElement)` to specify that element. - - -The following is an example of the 3rd option above. - -```html - - - -
- -
- - - - - -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/2jzeq1r6/) - -The element `div-video-container` is used as the UI this div contains the video element for showing the video stream. - - **NOTE**: The class name of the video element must be set to `dbrScanner-video`. - - ```html - - ``` - -### Cameras and Resolution Options - -Next, you can add the camera list and resolution list. - - If the class names match the default ones, `dbrScanner-sel-camera` and `dbrScanner-sel-resolution`, the library will automatically populate the lists and handle the camera/resolution switching automatically. - -```html - -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/nbj75vxu/) - -```html - -``` - 8 default resolutions are populated automatically. - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/25v08paf/) - -The following code shows how to display a custom set of resolution options. - -```html - -``` - - **Possible Issue**: Generally, you need to provide a resolution that the camera supports. However, in case a camera does not support the specified resolution, it usually uses the nearest supported resolution. As a result, the selected resolution may not be the actual resolution used. - - **Solution**: Add an option with the class name `dbrScanner-opt-gotResolution` (as shown above) which the library will then use to show the actual resolution being used. - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/tnfjks4q/) - diff --git a/programming-old/javascript/user-guide/basic-customizations-v8.0.0.md b/programming-old/javascript/user-guide/basic-customizations-v8.0.0.md deleted file mode 100644 index 70b7bfca..00000000 --- a/programming-old/javascript/user-guide/basic-customizations-v8.0.0.md +++ /dev/null @@ -1,237 +0,0 @@ ---- -layout: default-layout -title: v8.0.0 Basic Customizations - Dynamsoft Barcode Reader JavaScript Edition -description: This page shows how to customize basic features of Dynamsoft Barcode Reader JavaScript SDK. -keywords: user guide, basic customizations, initialize, javascript, js -needAutoGenerateSidebar: true -permalink: /programming/javascript/user-guide/basic-customizations-v8.0.0.html ---- - -# Basic Customizations - -## Initializing - -The library is based on the `WebAssembly` standard; therefore, **on first use**, it needs some time to download and compile the `wasm` files. After first use, the browser may cache the file. - -`Dynamsoft.DBR.BarcodeReader.loadWasm()` is the API to start the initialization. - -```javascript -try{ - await Dynamsoft.DBR.BarcodeReader.loadWasm(); -}catch(ex){ - console.error(ex); -} -``` - -Other APIs like `Dynamsoft.DBR.BarcodeReader.createInstance()` and `Dynamsoft.DBR.BarcodeScanner.createInstance()` will also call `loadWasm()` during initialization. The following demonstrates the most common usage. - -```javascript -let reader = null; -let scanner = null; -try{ - reader = await Dynamsoft.DBR.BarcodeReader.createInstance(); - scanner = await Dynamsoft.DBR.BarcodeScanner.createInstance(); -}catch(ex){ - console.error(ex); -} -``` - -*NOTE* - -Including the library with a script tag doesn't automatically initialize the library. For better performance, you may want to call `loadWasm()` to download and compile the wasm file in advance and create a reader or scanner instance later. - -Initialization consists of the following steps: - -* Download - -Download the necessary resources. Usually, we deploy the resources on CDN and set a long cache duration. *If your web server is faster, you should put the resources on your own server instead of using the CDN.* - -* Compile - -The `wasm` files are automatically compiled once downloaded. The compilation time varies among different devices & browsers. While it takes less than a second on latest phones or PCs, it may take much longer on older devices. - -* Initialize - -The library needs to initialize every time the page loads. The initialization means creating a `BarcodeReader` or `BarcodeScanner` instance with specified settings. - -## Configuring Scanner Settings - -When creating an instance of the `BarcodeScanner` object, there are several configuration options. The following code shows some of the most popular ones: - -```javascript -// set which camera and what resolution to use -await scanner.updateVideoSettings({ video: { width: 1280, height: 720, facingMode: "environment" } }); - -// use one of the built-in RuntimeSetting templates: "single" (decode single barcode, default mode), "speed", "balance", "coverage". "speed" is recommended for decoding from a video stream -await scanner.updateRuntimeSettings("speed"); - -// make changes to the template. The code snippet below demonstrates how to specify which symbologies are enabled -let runtimeSettings = await scanner.getRuntimeSettings(); -runtimeSettings.barcodeFormatIds = Dynamsoft.EnumBarcodeFormat.BF_ONED | Dynamsoft.EnumBarcodeFormat.BF_QR_CODE; -await scanner.updateRuntimeSettings(runtimeSettings); - -// set up the scanner behavior -let scanSettings = await scanner.getScanSettings(); -// disregard duplicated results found in a specified time period -scanSettings.duplicateForgetTime = 20000; -// set a scan interval so the library may release the CPU from time to time -scanSettings.intervalTime = 300; -await scanner.updateScanSettings(scanSettings); -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/yfkcajxz/) - -As you can see in the code, there are three types of configurations: - -- `get/updateVideoSettings`: Configures the data source, i.e., the video stream. These settings include which camera to use, the resolution, etc. Learn more [here](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia#Syntax). - -- `get/updateRuntimeSettings`: Configures the decode engine. Find a full list of these settings and their corresponding descriptions [here](../api-reference/global-interfaces.md#runtimesettings). For example, the following uses the built-in "speed" settings with updated `localizationModes`. - - ```javascript - await barcodeScanner.updateRuntimeSettings("speed"); - //await barcodeScanner.updateRuntimeSettings("balance"); //alternative - //await barcodeScanner.updateRuntimeSettings("coverage"); //alternative - let settings = await barcodeScanner.getRuntimeSettings(); - settings.localizationModes = [ - Dynamsoft.EnumLocalizationMode.LM_CONNECTED_BLOCKS, - Dynamsoft.EnumLocalizationMode.LM_SCAN_DIRECTLY, - Dynamsoft.EnumLocalizationMode.LM_LINES, 0, 0, 0, 0, 0]; - await barcodeScanner.updateRuntimeSettings(settings); - ``` - Try in [JSFiddle](https://jsfiddle.net/DynamsoftTeam/f24h8c1m/). - -- `get/updateScanSettings`: Configures the behavior of the scanner which includes `duplicateForgetTime`, `intervalTime` and `filter`, etc. - -## Customizing the UI - -The library provides a built-in UI for the `BarcodeScanner`object where the default scanner UI is defined in the file `dist/dbr.scanner.html`. There are a few ways to customize it: - -* Modify the file `dist/dbr.scanner.html` directly. - - This option is only possible when you deploy these files yourself instead of using the CDN. - -* Copy the file `dist/dbr.scanner.html` to your application, modify it and specify the new file as the default UI with the API `defaultUIElementURL` - - ```javascript - Dynamsoft.DBR.BarcodeScanner.defaultUIElementURL = url; - ``` - - *Note* - - You must set `defaultUIElementURL` before you call `createInstance`. - -* Build the UI element into your own web page and call `scanner.setUIElement(HTMLElement)` to specify that element. -* Append the default UI element to an element on your page. After that, you can customize it further. The following shows how to append the default UI to a DIV and hide the close button. - - ```html -
- ``` - - ```javascript - document.getElementById('scannerUI').appendChild(scanner.getUIElement()); - document.getElementsByClassName('dbrScanner-btn-close')[0].hidden = true; - ``` - -The following is an example of the 3rd option above. - -```html - - - -
- -
- - - - - -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/2jzeq1r6/) - -*NOTE* - -The video element must contain the class `dbrScanner-video` so that it can be used. - -```html - -``` - -### Cameras and Resolution Options - -Next, you can add the camera list and resolution list inside the UI element. In our case, the element would be `document.getElementById('div-video-container')`. - -If the class names match the default ones, `dbrScanner-sel-camera` and `dbrScanner-sel-resolution`, the library will automatically populate the lists and handle the camera/resolution switching automatically. - -```html - -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/nbj75vxu/) - -```html - -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/25v08paf/) - -*Note* - -By default, 8 hard-coded resolutions will be populated as options. - -The following code shows how to display a custom set of resolution options. - -```html - -``` - -*NOTE* - -Generally, you need to provide a resolution that the camera supports. However, in case a camera does not support the specified resolution, it usually uses the nearest supported resolution. As a result, the selected resolution may not be the actual resolution used. In this case, add an option with the class name `dbrScanner-opt-gotResolution` (as shown above) and the library will then use it to show the actual resolution. - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/tnfjks4q/) - -## Decode Barcodes from Existing Video Stream - -In v8.0, we introduced a new feature to decode barcodes from an existing video stream. To set the existing video stream, we'll use [setUIElement()](../api-reference/BarcodeScanner/methods/initialize-and-destroy.md#setuielement). - -```html - - - -
- -
- - - - - -``` -*NOTE* - -The video element must contain the class `dbrScanner-existingVideo`. diff --git a/programming-old/javascript/user-guide/basic-customizations-v8.1.0.md b/programming-old/javascript/user-guide/basic-customizations-v8.1.0.md deleted file mode 100644 index 536a7b0a..00000000 --- a/programming-old/javascript/user-guide/basic-customizations-v8.1.0.md +++ /dev/null @@ -1,237 +0,0 @@ ---- -layout: default-layout -title: v8.1.0 Basic Customizations - Dynamsoft Barcode Reader JavaScript Edition -description: This page shows how to customize basic features of Dynamsoft Barcode Reader JavaScript SDK. -keywords: user guide, basic customizations, initialize, javascript, js -needAutoGenerateSidebar: true -permalink: /programming/javascript/user-guide/basic-customizations-v8.1.0.html ---- - -# Basic Customizations - -## Initializing - -The library is based on the `WebAssembly` standard; therefore, **on first use**, it needs some time to download and compile the `wasm` files. After first use, the browser may cache the file. - -`Dynamsoft.DBR.BarcodeReader.loadWasm()` is the API to start the initialization. - -```javascript -try{ - await Dynamsoft.DBR.BarcodeReader.loadWasm(); -}catch(ex){ - console.error(ex); -} -``` - -Other APIs like `Dynamsoft.DBR.BarcodeReader.createInstance()` and `Dynamsoft.DBR.BarcodeScanner.createInstance()` will also call `loadWasm()` during initialization. The following demonstrates the most common usage. - -```javascript -let reader = null; -let scanner = null; -try{ - reader = await Dynamsoft.DBR.BarcodeReader.createInstance(); - scanner = await Dynamsoft.DBR.BarcodeScanner.createInstance(); -}catch(ex){ - console.error(ex); -} -``` - -*NOTE* - -Including the library with a script tag doesn't automatically initialize the library. For better performance, you may want to call `loadWasm()` to download and compile the wasm file in advance and create a reader or scanner instance later. - -Initialization consists of the following steps: - -* Download - -Download the necessary resources. Usually, we deploy the resources on CDN and set a long cache duration. *If your web server is faster, you should put the resources on your own server instead of using the CDN.* - -* Compile - -The `wasm` files are automatically compiled once downloaded. The compilation time varies among different devices & browsers. While it takes less than a second on latest phones or PCs, it may take much longer on older devices. - -* Initialize - -The library needs to initialize every time the page loads. The initialization means creating a `BarcodeReader` or `BarcodeScanner` instance with specified settings. - -## Configuring Scanner Settings - -When creating an instance of the `BarcodeScanner` object, there are several configuration options. The following code shows some of the most popular ones: - -```javascript -// set which camera and what resolution to use -await scanner.updateVideoSettings({ video: { width: 1280, height: 720, facingMode: "environment" } }); - -// use one of the built-in RuntimeSetting templates: "single" (decode single barcode, default mode), "speed", "balance", "coverage". "speed" is recommended for decoding from a video stream -await scanner.updateRuntimeSettings("speed"); - -// make changes to the template. The code snippet below demonstrates how to specify which symbologies are enabled -let runtimeSettings = await scanner.getRuntimeSettings(); -runtimeSettings.barcodeFormatIds = Dynamsoft.EnumBarcodeFormat.BF_ONED | Dynamsoft.EnumBarcodeFormat.BF_QR_CODE; -await scanner.updateRuntimeSettings(runtimeSettings); - -// set up the scanner behavior -let scanSettings = await scanner.getScanSettings(); -// disregard duplicated results found in a specified time period -scanSettings.duplicateForgetTime = 20000; -// set a scan interval so the library may release the CPU from time to time -scanSettings.intervalTime = 300; -await scanner.updateScanSettings(scanSettings); -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/yfkcajxz/) - -As you can see in the code, there are three types of configurations: - -- `get/updateVideoSettings`: Configures the data source, i.e., the video stream. These settings include which camera to use, the resolution, etc. Learn more [here](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia#Syntax). - -- `get/updateRuntimeSettings`: Configures the decode engine. Find a full list of these settings and their corresponding descriptions [here](../api-reference/global-interfaces.md#runtimesettings). For example, the following uses the built-in "speed" settings with updated `localizationModes`. - - ```javascript - await barcodeScanner.updateRuntimeSettings("speed"); - //await barcodeScanner.updateRuntimeSettings("balance"); //alternative - //await barcodeScanner.updateRuntimeSettings("coverage"); //alternative - let settings = await barcodeScanner.getRuntimeSettings(); - settings.localizationModes = [ - Dynamsoft.EnumLocalizationMode.LM_CONNECTED_BLOCKS, - Dynamsoft.EnumLocalizationMode.LM_SCAN_DIRECTLY, - Dynamsoft.EnumLocalizationMode.LM_LINES, 0, 0, 0, 0, 0]; - await barcodeScanner.updateRuntimeSettings(settings); - ``` - Try in [JSFiddle](https://jsfiddle.net/DynamsoftTeam/f24h8c1m/). - -- `get/updateScanSettings`: Configures the behavior of the scanner which includes `duplicateForgetTime`, `intervalTime` and `filter`, etc. - -## Customizing the UI - -The library provides a built-in UI for the `BarcodeScanner`object where the default scanner UI is defined in the file `dist/dbr.scanner.html`. There are a few ways to customize it: - -* Modify the file `dist/dbr.scanner.html` directly. - - This option is only possible when you deploy these files yourself instead of using the CDN. - -* Copy the file `dist/dbr.scanner.html` to your application, modify it and specify the new file as the default UI with the API `defaultUIElementURL` - - ```javascript - Dynamsoft.DBR.BarcodeScanner.defaultUIElementURL = url; - ``` - - *Note* - - You must set `defaultUIElementURL` before you call `createInstance`. - -* Build the UI element into your own web page and call `scanner.setUIElement(HTMLElement)` to specify that element. -* Append the default UI element to an element on your page. After that, you can customize it further. The following shows how to append the default UI to a DIV and hide the close button. - - ```html -
- ``` - - ```javascript - document.getElementById('scannerUI').appendChild(scanner.getUIElement()); - document.getElementsByClassName('dbrScanner-btn-close')[0].hidden = true; - ``` - -The following is an example of the 3rd option above. - -```html - - - -
- -
- - - - - -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/2jzeq1r6/) - -*NOTE* - -The video element must contain the class `dbrScanner-video` so that it can be used. - -```html - -``` - -### Cameras and Resolution Options - -Next, you can add the camera list and resolution list inside the UI element. In our case, the element would be `document.getElementById('div-video-container')`. - -If the class names match the default ones, `dbrScanner-sel-camera` and `dbrScanner-sel-resolution`, the library will automatically populate the lists and handle the camera/resolution switching automatically. - -```html - -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/nbj75vxu/) - -```html - -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/25v08paf/) - -*Note* - -By default, 8 hard-coded resolutions will be populated as options. - -The following code shows how to display a custom set of resolution options. - -```html - -``` - -*NOTE* - -Generally, you need to provide a resolution that the camera supports. However, in case a camera does not support the specified resolution, it usually uses the nearest supported resolution. As a result, the selected resolution may not be the actual resolution used. In this case, add an option with the class name `dbrScanner-opt-gotResolution` (as shown above) and the library will then use it to show the actual resolution. - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/tnfjks4q/) - -## Decode Barcodes from Existing Video Stream - -In v8.0, we introduced a new feature to decode barcodes from an existing video stream. To set the existing video stream, we'll use [setUIElement()](../api-reference/BarcodeScanner/methods/initialize-and-destroy.md#setuielement). - -```html - - - -
- -
- - - - - -``` -*NOTE* - -The video element must contain the class `dbrScanner-existingVideo`. diff --git a/programming-old/javascript/user-guide/basic-customizations-v8.1.2.md b/programming-old/javascript/user-guide/basic-customizations-v8.1.2.md deleted file mode 100644 index c3fad73e..00000000 --- a/programming-old/javascript/user-guide/basic-customizations-v8.1.2.md +++ /dev/null @@ -1,237 +0,0 @@ ---- -layout: default-layout -title: v8.1.2 Basic Customizations - Dynamsoft Barcode Reader JavaScript Edition -description: This page shows how to customize basic features of Dynamsoft Barcode Reader JavaScript SDK. -keywords: user guide, basic customizations, initialize, javascript, js -needAutoGenerateSidebar: true -permalink: /programming/javascript/user-guide/basic-customizations-v8.1.2.html ---- - -# Basic Customizations - -## Initializing - -The library is based on the `WebAssembly` standard; therefore, **on first use**, it needs some time to download and compile the `wasm` files. After first use, the browser may cache the file. - -`Dynamsoft.DBR.BarcodeReader.loadWasm()` is the API to start the initialization. - -```javascript -try{ - await Dynamsoft.DBR.BarcodeReader.loadWasm(); -}catch(ex){ - console.error(ex); -} -``` - -Other APIs like `Dynamsoft.DBR.BarcodeReader.createInstance()` and `Dynamsoft.DBR.BarcodeScanner.createInstance()` will also call `loadWasm()` during initialization. The following demonstrates the most common usage. - -```javascript -let reader = null; -let scanner = null; -try{ - reader = await Dynamsoft.DBR.BarcodeReader.createInstance(); - scanner = await Dynamsoft.DBR.BarcodeScanner.createInstance(); -}catch(ex){ - console.error(ex); -} -``` - -*NOTE* - -Including the library with a script tag doesn't automatically initialize the library. For better performance, you may want to call `loadWasm()` to download and compile the wasm file in advance and create a reader or scanner instance later. - -Initialization consists of the following steps: - -* Download - -Download the necessary resources. Usually, we deploy the resources on CDN and set a long cache duration. *If your web server is faster, you should put the resources on your own server instead of using the CDN.* - -* Compile - -The `wasm` files are automatically compiled once downloaded. The compilation time varies among different devices & browsers. While it takes less than a second on latest phones or PCs, it may take much longer on older devices. - -* Initialize - -The library needs to initialize every time the page loads. The initialization means creating a `BarcodeReader` or `BarcodeScanner` instance with specified settings. - -## Configuring Scanner Settings - -When creating an instance of the `BarcodeScanner` object, there are several configuration options. The following code shows some of the most popular ones: - -```javascript -// set which camera and what resolution to use -await scanner.updateVideoSettings({ video: { width: 1280, height: 720, facingMode: "environment" } }); - -// use one of the built-in RuntimeSetting templates: "single" (decode single barcode, default mode), "speed", "balance", "coverage". "speed" is recommended for decoding from a video stream -await scanner.updateRuntimeSettings("speed"); - -// make changes to the template. The code snippet below demonstrates how to specify which symbologies are enabled -let runtimeSettings = await scanner.getRuntimeSettings(); -runtimeSettings.barcodeFormatIds = Dynamsoft.EnumBarcodeFormat.BF_ONED | Dynamsoft.EnumBarcodeFormat.BF_QR_CODE; -await scanner.updateRuntimeSettings(runtimeSettings); - -// set up the scanner behavior -let scanSettings = await scanner.getScanSettings(); -// disregard duplicated results found in a specified time period -scanSettings.duplicateForgetTime = 20000; -// set a scan interval so the library may release the CPU from time to time -scanSettings.intervalTime = 300; -await scanner.updateScanSettings(scanSettings); -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/yfkcajxz/) - -As you can see in the code, there are three types of configurations: - -- `get/updateVideoSettings`: Configures the data source, i.e., the video stream. These settings include which camera to use, the resolution, etc. Learn more [here](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia#Syntax). - -- `get/updateRuntimeSettings`: Configures the decode engine. Find a full list of these settings and their corresponding descriptions [here](../api-reference/global-interfaces.md#runtimesettings). For example, the following uses the built-in "speed" settings with updated `localizationModes`. - - ```javascript - await barcodeScanner.updateRuntimeSettings("speed"); - //await barcodeScanner.updateRuntimeSettings("balance"); //alternative - //await barcodeScanner.updateRuntimeSettings("coverage"); //alternative - let settings = await barcodeScanner.getRuntimeSettings(); - settings.localizationModes = [ - Dynamsoft.EnumLocalizationMode.LM_CONNECTED_BLOCKS, - Dynamsoft.EnumLocalizationMode.LM_SCAN_DIRECTLY, - Dynamsoft.EnumLocalizationMode.LM_LINES, 0, 0, 0, 0, 0]; - await barcodeScanner.updateRuntimeSettings(settings); - ``` - Try in [JSFiddle](https://jsfiddle.net/DynamsoftTeam/f24h8c1m/). - -- `get/updateScanSettings`: Configures the behavior of the scanner which includes `duplicateForgetTime`, `intervalTime` and `filter`, etc. - -## Customizing the UI - -The library provides a built-in UI for the `BarcodeScanner`object where the default scanner UI is defined in the file `dist/dbr.scanner.html`. There are a few ways to customize it: - -* Modify the file `dist/dbr.scanner.html` directly. - - This option is only possible when you deploy these files yourself instead of using the CDN. - -* Copy the file `dist/dbr.scanner.html` to your application, modify it and specify the new file as the default UI with the API `defaultUIElementURL` - - ```javascript - Dynamsoft.DBR.BarcodeScanner.defaultUIElementURL = url; - ``` - - *Note* - - You must set `defaultUIElementURL` before you call `createInstance`. - -* Build the UI element into your own web page and call `scanner.setUIElement(HTMLElement)` to specify that element. -* Append the default UI element to an element on your page. After that, you can customize it further. The following shows how to append the default UI to a DIV and hide the close button. - - ```html -
- ``` - - ```javascript - document.getElementById('scannerUI').appendChild(scanner.getUIElement()); - document.getElementsByClassName('dbrScanner-btn-close')[0].hidden = true; - ``` - -The following is an example of the 3rd option above. - -```html - - - -
- -
- - - - - -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/2jzeq1r6/) - -*NOTE* - -The video element must contain the class `dbrScanner-video` so that it can be used. - -```html - -``` - -### Cameras and Resolution Options - -Next, you can add the camera list and resolution list inside the UI element. In our case, the element would be `document.getElementById('div-video-container')`. - -If the class names match the default ones, `dbrScanner-sel-camera` and `dbrScanner-sel-resolution`, the library will automatically populate the lists and handle the camera/resolution switching automatically. - -```html - -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/nbj75vxu/) - -```html - -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/25v08paf/) - -*Note* - -By default, 8 hard-coded resolutions will be populated as options. - -The following code shows how to display a custom set of resolution options. - -```html - -``` - -*NOTE* - -Generally, you need to provide a resolution that the camera supports. However, in case a camera does not support the specified resolution, it usually uses the nearest supported resolution. As a result, the selected resolution may not be the actual resolution used. In this case, add an option with the class name `dbrScanner-opt-gotResolution` (as shown above) and the library will then use it to show the actual resolution. - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/tnfjks4q/) - -## Decode Barcodes from Existing Video Stream - -In v8.0, we introduced a new feature to decode barcodes from an existing video stream. To set the existing video stream, we'll use [setUIElement()](../api-reference/BarcodeScanner/methods/initialize-and-destroy.md#setuielement). - -```html - - - -
- -
- - - - - -``` -*NOTE* - -The video element must contain the class `dbrScanner-existingVideo`. diff --git a/programming-old/javascript/user-guide/basic-customizations-v8.1.3.md b/programming-old/javascript/user-guide/basic-customizations-v8.1.3.md deleted file mode 100644 index 893fc504..00000000 --- a/programming-old/javascript/user-guide/basic-customizations-v8.1.3.md +++ /dev/null @@ -1,237 +0,0 @@ ---- -layout: default-layout -title: v8.1.3 Basic Customizations - Dynamsoft Barcode Reader JavaScript Edition -description: This page shows how to customize basic features of Dynamsoft Barcode Reader JavaScript SDK. -keywords: user guide, basic customizations, initialize, javascript, js -needAutoGenerateSidebar: true -permalink: /programming/javascript/user-guide/basic-customizations-v8.1.3.html ---- - -# Basic Customizations - -## Initializing - -The library is based on the `WebAssembly` standard; therefore, **on first use**, it needs some time to download and compile the `wasm` files. After first use, the browser may cache the file. - -`Dynamsoft.DBR.BarcodeReader.loadWasm()` is the API to start the initialization. - -```javascript -try{ - await Dynamsoft.DBR.BarcodeReader.loadWasm(); -}catch(ex){ - console.error(ex); -} -``` - -Other APIs like `Dynamsoft.DBR.BarcodeReader.createInstance()` and `Dynamsoft.DBR.BarcodeScanner.createInstance()` will also call `loadWasm()` during initialization. The following demonstrates the most common usage. - -```javascript -let reader = null; -let scanner = null; -try{ - reader = await Dynamsoft.DBR.BarcodeReader.createInstance(); - scanner = await Dynamsoft.DBR.BarcodeScanner.createInstance(); -}catch(ex){ - console.error(ex); -} -``` - -*NOTE* - -Including the library with a script tag doesn't automatically initialize the library. For better performance, you may want to call `loadWasm()` to download and compile the wasm file in advance and create a reader or scanner instance later. - -Initialization consists of the following steps: - -* Download - -Download the necessary resources. Usually, we deploy the resources on CDN and set a long cache duration. *If your web server is faster, you should put the resources on your own server instead of using the CDN.* - -* Compile - -The `wasm` files are automatically compiled once downloaded. The compilation time varies among different devices & browsers. While it takes less than a second on latest phones or PCs, it may take much longer on older devices. - -* Initialize - -The library needs to initialize every time the page loads. The initialization means creating a `BarcodeReader` or `BarcodeScanner` instance with specified settings. - -## Configuring Scanner Settings - -When creating an instance of the `BarcodeScanner` object, there are several configuration options. The following code shows some of the most popular ones: - -```javascript -// set which camera and what resolution to use -await scanner.updateVideoSettings({ video: { width: 1280, height: 720, facingMode: "environment" } }); - -// use one of the built-in RuntimeSetting templates: "single" (decode single barcode, default mode), "speed", "balance", "coverage". "speed" is recommended for decoding from a video stream -await scanner.updateRuntimeSettings("speed"); - -// make changes to the template. The code snippet below demonstrates how to specify which symbologies are enabled -let runtimeSettings = await scanner.getRuntimeSettings(); -runtimeSettings.barcodeFormatIds = Dynamsoft.EnumBarcodeFormat.BF_ONED | Dynamsoft.EnumBarcodeFormat.BF_QR_CODE; -await scanner.updateRuntimeSettings(runtimeSettings); - -// set up the scanner behavior -let scanSettings = await scanner.getScanSettings(); -// disregard duplicated results found in a specified time period -scanSettings.duplicateForgetTime = 20000; -// set a scan interval so the library may release the CPU from time to time -scanSettings.intervalTime = 300; -await scanner.updateScanSettings(scanSettings); -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/yfkcajxz/) - -As you can see in the code, there are three types of configurations: - -- `get/updateVideoSettings`: Configures the data source, i.e., the video stream. These settings include which camera to use, the resolution, etc. Learn more [here](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia#Syntax). - -- `get/updateRuntimeSettings`: Configures the decode engine. Find a full list of these settings and their corresponding descriptions [here](../api-reference/global-interfaces.md#runtimesettings). For example, the following uses the built-in "speed" settings with updated `localizationModes`. - - ```javascript - await barcodeScanner.updateRuntimeSettings("speed"); - //await barcodeScanner.updateRuntimeSettings("balance"); //alternative - //await barcodeScanner.updateRuntimeSettings("coverage"); //alternative - let settings = await barcodeScanner.getRuntimeSettings(); - settings.localizationModes = [ - Dynamsoft.EnumLocalizationMode.LM_CONNECTED_BLOCKS, - Dynamsoft.EnumLocalizationMode.LM_SCAN_DIRECTLY, - Dynamsoft.EnumLocalizationMode.LM_LINES, 0, 0, 0, 0, 0]; - await barcodeScanner.updateRuntimeSettings(settings); - ``` - Try in [JSFiddle](https://jsfiddle.net/DynamsoftTeam/f24h8c1m/). - -- `get/updateScanSettings`: Configures the behavior of the scanner which includes `duplicateForgetTime`, `intervalTime` and `filter`, etc. - -## Customizing the UI - -The library provides a built-in UI for the `BarcodeScanner`object where the default scanner UI is defined in the file `dist/dbr.scanner.html`. There are a few ways to customize it: - -* Modify the file `dist/dbr.scanner.html` directly. - - This option is only possible when you deploy these files yourself instead of using the CDN. - -* Copy the file `dist/dbr.scanner.html` to your application, modify it and specify the new file as the default UI with the API `defaultUIElementURL` - - ```javascript - Dynamsoft.DBR.BarcodeScanner.defaultUIElementURL = url; - ``` - - *Note* - - You must set `defaultUIElementURL` before you call `createInstance`. - -* Build the UI element into your own web page and call `scanner.setUIElement(HTMLElement)` to specify that element. -* Append the default UI element to an element on your page. After that, you can customize it further. The following shows how to append the default UI to a DIV and hide the close button. - - ```html -
- ``` - - ```javascript - document.getElementById('scannerUI').appendChild(scanner.getUIElement()); - document.getElementsByClassName('dbrScanner-btn-close')[0].hidden = true; - ``` - -The following is an example of the 3rd option above. - -```html - - - -
- -
- - - - - -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/2jzeq1r6/) - -*NOTE* - -The video element must contain the class `dbrScanner-video` so that it can be used. - -```html - -``` - -### Cameras and Resolution Options - -Next, you can add the camera list and resolution list inside the UI element. In our case, the element would be `document.getElementById('div-video-container')`. - -If the class names match the default ones, `dbrScanner-sel-camera` and `dbrScanner-sel-resolution`, the library will automatically populate the lists and handle the camera/resolution switching automatically. - -```html - -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/nbj75vxu/) - -```html - -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/25v08paf/) - -*Note* - -By default, 8 hard-coded resolutions will be populated as options. - -The following code shows how to display a custom set of resolution options. - -```html - -``` - -*NOTE* - -Generally, you need to provide a resolution that the camera supports. However, in case a camera does not support the specified resolution, it usually uses the nearest supported resolution. As a result, the selected resolution may not be the actual resolution used. In this case, add an option with the class name `dbrScanner-opt-gotResolution` (as shown above) and the library will then use it to show the actual resolution. - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/tnfjks4q/) - -## Decode Barcodes from Existing Video Stream - -In v8.0, we introduced a new feature to decode barcodes from an existing video stream. To set the existing video stream, we'll use [setUIElement()](../api-reference/BarcodeScanner/methods/initialize-and-destroy.md#setuielement). - -```html - - - -
- -
- - - - - -``` -*NOTE* - -The video element must contain the class `dbrScanner-existingVideo`. diff --git a/programming-old/javascript/user-guide/basic-customizations-v8.2.0.md b/programming-old/javascript/user-guide/basic-customizations-v8.2.0.md deleted file mode 100644 index 47a816fd..00000000 --- a/programming-old/javascript/user-guide/basic-customizations-v8.2.0.md +++ /dev/null @@ -1,237 +0,0 @@ ---- -layout: default-layout -title: v8.2.0 Basic Customizations - Dynamsoft Barcode Reader JavaScript Edition -description: This page shows how to customize basic features of Dynamsoft Barcode Reader JavaScript SDK. -keywords: user guide, basic customizations, initialize, javascript, js -needAutoGenerateSidebar: true -permalink: /programming/javascript/user-guide/basic-customizations-v8.2.0.html ---- - -# Basic Customizations - -## Initializing - -The library is based on the `WebAssembly` standard; therefore, **on first use**, it needs some time to download and compile the `wasm` files. After first use, the browser may cache the file. - -`Dynamsoft.DBR.BarcodeReader.loadWasm()` is the API to start the initialization. - -```javascript -try{ - await Dynamsoft.DBR.BarcodeReader.loadWasm(); -}catch(ex){ - console.error(ex); -} -``` - -Other APIs like `Dynamsoft.DBR.BarcodeReader.createInstance()` and `Dynamsoft.DBR.BarcodeScanner.createInstance()` will also call `loadWasm()` during initialization. The following demonstrates the most common usage. - -```javascript -let reader = null; -let scanner = null; -try{ - reader = await Dynamsoft.DBR.BarcodeReader.createInstance(); - scanner = await Dynamsoft.DBR.BarcodeScanner.createInstance(); -}catch(ex){ - console.error(ex); -} -``` - -*NOTE* - -Including the library with a script tag doesn't automatically initialize the library. For better performance, you may want to call `loadWasm()` to download and compile the wasm file in advance and create a reader or scanner instance later. - -Initialization consists of the following steps: - -* Download - -Download the necessary resources. Usually, we deploy the resources on CDN and set a long cache duration. *If your web server is faster, you should put the resources on your own server instead of using the CDN.* - -* Compile - -The `wasm` files are automatically compiled once downloaded. The compilation time varies among different devices & browsers. While it takes less than a second on latest phones or PCs, it may take much longer on older devices. - -* Initialize - -The library needs to initialize every time the page loads. The initialization means creating a `BarcodeReader` or `BarcodeScanner` instance with specified settings. - -## Configuring Scanner Settings - -When creating an instance of the `BarcodeScanner` object, there are several configuration options. The following code shows some of the most popular ones: - -```javascript -// set which camera and what resolution to use -await scanner.updateVideoSettings({ video: { width: 1280, height: 720, facingMode: "environment" } }); - -// use one of the built-in RuntimeSetting templates: "single" (decode single barcode, default mode), "speed", "balance", "coverage". "speed" is recommended for decoding from a video stream -await scanner.updateRuntimeSettings("speed"); - -// make changes to the template. The code snippet below demonstrates how to specify which symbologies are enabled -let runtimeSettings = await scanner.getRuntimeSettings(); -runtimeSettings.barcodeFormatIds = Dynamsoft.EnumBarcodeFormat.BF_ONED | Dynamsoft.EnumBarcodeFormat.BF_QR_CODE; -await scanner.updateRuntimeSettings(runtimeSettings); - -// set up the scanner behavior -let scanSettings = await scanner.getScanSettings(); -// disregard duplicated results found in a specified time period -scanSettings.duplicateForgetTime = 20000; -// set a scan interval so the library may release the CPU from time to time -scanSettings.intervalTime = 300; -await scanner.updateScanSettings(scanSettings); -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/yfkcajxz/) - -As you can see in the code, there are three types of configurations: - -- `get/updateVideoSettings`: Configures the data source, i.e., the video stream. These settings include which camera to use, the resolution, etc. Learn more [here](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia#Syntax). - -- `get/updateRuntimeSettings`: Configures the decode engine. Find a full list of these settings and their corresponding descriptions [here](../api-reference/global-interfaces.md#runtimesettings). For example, the following uses the built-in "speed" settings with updated `localizationModes`. - - ```javascript - await barcodeScanner.updateRuntimeSettings("speed"); - //await barcodeScanner.updateRuntimeSettings("balance"); //alternative - //await barcodeScanner.updateRuntimeSettings("coverage"); //alternative - let settings = await barcodeScanner.getRuntimeSettings(); - settings.localizationModes = [ - Dynamsoft.EnumLocalizationMode.LM_CONNECTED_BLOCKS, - Dynamsoft.EnumLocalizationMode.LM_SCAN_DIRECTLY, - Dynamsoft.EnumLocalizationMode.LM_LINES, 0, 0, 0, 0, 0]; - await barcodeScanner.updateRuntimeSettings(settings); - ``` - Try in [JSFiddle](https://jsfiddle.net/DynamsoftTeam/f24h8c1m/). - -- `get/updateScanSettings`: Configures the behavior of the scanner which includes `duplicateForgetTime`, `intervalTime` and `filter`, etc. - -## Customizing the UI - -The library provides a built-in UI for the `BarcodeScanner`object where the default scanner UI is defined in the file `dist/dbr.scanner.html`. There are a few ways to customize it: - -* Modify the file `dist/dbr.scanner.html` directly. - - This option is only possible when you deploy these files yourself instead of using the CDN. - -* Copy the file `dist/dbr.scanner.html` to your application, modify it and specify the new file as the default UI with the API `defaultUIElementURL` - - ```javascript - Dynamsoft.DBR.BarcodeScanner.defaultUIElementURL = url; - ``` - - *Note* - - You must set `defaultUIElementURL` before you call `createInstance`. - -* Build the UI element into your own web page and call `scanner.setUIElement(HTMLElement)` to specify that element. -* Append the default UI element to an element on your page. After that, you can customize it further. The following shows how to append the default UI to a DIV and hide the close button. - - ```html -
- ``` - - ```javascript - document.getElementById('scannerUI').appendChild(scanner.getUIElement()); - document.getElementsByClassName('dbrScanner-btn-close')[0].hidden = true; - ``` - -The following is an example of the 3rd option above. - -```html - - - -
- -
- - - - - -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/2jzeq1r6/) - -*NOTE* - -The video element must contain the class `dbrScanner-video` so that it can be used. - -```html - -``` - -### Cameras and Resolution Options - -Next, you can add the camera list and resolution list inside the UI element. In our case, the element would be `document.getElementById('div-video-container')`. - -If the class names match the default ones, `dbrScanner-sel-camera` and `dbrScanner-sel-resolution`, the library will automatically populate the lists and handle the camera/resolution switching automatically. - -```html - -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/nbj75vxu/) - -```html - -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/25v08paf/) - -*Note* - -By default, 8 hard-coded resolutions will be populated as options. - -The following code shows how to display a custom set of resolution options. - -```html - -``` - -*NOTE* - -Generally, you need to provide a resolution that the camera supports. However, in case a camera does not support the specified resolution, it usually uses the nearest supported resolution. As a result, the selected resolution may not be the actual resolution used. In this case, add an option with the class name `dbrScanner-opt-gotResolution` (as shown above) and the library will then use it to show the actual resolution. - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/tnfjks4q/) - -## Decode Barcodes from Existing Video Stream - -In v8.0, we introduced a new feature to decode barcodes from an existing video stream. To set the existing video stream, we'll use [setUIElement()](../api-reference/BarcodeScanner/methods/initialize-and-destroy.md#setuielement). - -```html - - - -
- -
- - - - - -``` -*NOTE* - -The video element must contain the class `dbrScanner-existingVideo`. diff --git a/programming-old/javascript/user-guide/basic-customizations-v8.2.1.md b/programming-old/javascript/user-guide/basic-customizations-v8.2.1.md deleted file mode 100644 index c292d335..00000000 --- a/programming-old/javascript/user-guide/basic-customizations-v8.2.1.md +++ /dev/null @@ -1,237 +0,0 @@ ---- -layout: default-layout -title: v8.2.1 Basic Customizations - Dynamsoft Barcode Reader JavaScript Edition -description: This page shows how to customize basic features of Dynamsoft Barcode Reader JavaScript SDK. -keywords: user guide, basic customizations, initialize, javascript, js -needAutoGenerateSidebar: true -permalink: /programming/javascript/user-guide/basic-customizations-v8.2.1.html ---- - -# Basic Customizations - -## Initializing - -The library is based on the `WebAssembly` standard; therefore, **on first use**, it needs some time to download and compile the `wasm` files. After first use, the browser may cache the file. - -`Dynamsoft.DBR.BarcodeReader.loadWasm()` is the API to start the initialization. - -```javascript -try{ - await Dynamsoft.DBR.BarcodeReader.loadWasm(); -}catch(ex){ - console.error(ex); -} -``` - -Other APIs like `Dynamsoft.DBR.BarcodeReader.createInstance()` and `Dynamsoft.DBR.BarcodeScanner.createInstance()` will also call `loadWasm()` during initialization. The following demonstrates the most common usage. - -```javascript -let reader = null; -let scanner = null; -try{ - reader = await Dynamsoft.DBR.BarcodeReader.createInstance(); - scanner = await Dynamsoft.DBR.BarcodeScanner.createInstance(); -}catch(ex){ - console.error(ex); -} -``` - -*NOTE* - -Including the library with a script tag doesn't automatically initialize the library. For better performance, you may want to call `loadWasm()` to download and compile the wasm file in advance and create a reader or scanner instance later. - -Initialization consists of the following steps: - -* Download - -Download the necessary resources. Usually, we deploy the resources on CDN and set a long cache duration. *If your web server is faster, you should put the resources on your own server instead of using the CDN.* - -* Compile - -The `wasm` files are automatically compiled once downloaded. The compilation time varies among different devices & browsers. While it takes less than a second on latest phones or PCs, it may take much longer on older devices. - -* Initialize - -The library needs to initialize every time the page loads. The initialization means creating a `BarcodeReader` or `BarcodeScanner` instance with specified settings. - -## Configuring Scanner Settings - -When creating an instance of the `BarcodeScanner` object, there are several configuration options. The following code shows some of the most popular ones: - -```javascript -// set which camera and what resolution to use -await scanner.updateVideoSettings({ video: { width: 1280, height: 720, facingMode: "environment" } }); - -// use one of the built-in RuntimeSetting templates: "single" (decode single barcode, default mode), "speed", "balance", "coverage". "speed" is recommended for decoding from a video stream -await scanner.updateRuntimeSettings("speed"); - -// make changes to the template. The code snippet below demonstrates how to specify which symbologies are enabled -let runtimeSettings = await scanner.getRuntimeSettings(); -runtimeSettings.barcodeFormatIds = Dynamsoft.EnumBarcodeFormat.BF_ONED | Dynamsoft.EnumBarcodeFormat.BF_QR_CODE; -await scanner.updateRuntimeSettings(runtimeSettings); - -// set up the scanner behavior -let scanSettings = await scanner.getScanSettings(); -// disregard duplicated results found in a specified time period -scanSettings.duplicateForgetTime = 20000; -// set a scan interval so the library may release the CPU from time to time -scanSettings.intervalTime = 300; -await scanner.updateScanSettings(scanSettings); -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/yfkcajxz/) - -As you can see in the code, there are three types of configurations: - -- `get/updateVideoSettings`: Configures the data source, i.e., the video stream. These settings include which camera to use, the resolution, etc. Learn more [here](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia#Syntax). - -- `get/updateRuntimeSettings`: Configures the decode engine. Find a full list of these settings and their corresponding descriptions [here](../api-reference/global-interfaces.md#runtimesettings). For example, the following uses the built-in "speed" settings with updated `localizationModes`. - - ```javascript - await barcodeScanner.updateRuntimeSettings("speed"); - //await barcodeScanner.updateRuntimeSettings("balance"); //alternative - //await barcodeScanner.updateRuntimeSettings("coverage"); //alternative - let settings = await barcodeScanner.getRuntimeSettings(); - settings.localizationModes = [ - Dynamsoft.EnumLocalizationMode.LM_CONNECTED_BLOCKS, - Dynamsoft.EnumLocalizationMode.LM_SCAN_DIRECTLY, - Dynamsoft.EnumLocalizationMode.LM_LINES, 0, 0, 0, 0, 0]; - await barcodeScanner.updateRuntimeSettings(settings); - ``` - Try in [JSFiddle](https://jsfiddle.net/DynamsoftTeam/f24h8c1m/). - -- `get/updateScanSettings`: Configures the behavior of the scanner which includes `duplicateForgetTime`, `intervalTime` and `filter`, etc. - -## Customizing the UI - -The library provides a built-in UI for the `BarcodeScanner`object where the default scanner UI is defined in the file `dist/dbr.scanner.html`. There are a few ways to customize it: - -* Modify the file `dist/dbr.scanner.html` directly. - - This option is only possible when you deploy these files yourself instead of using the CDN. - -* Copy the file `dist/dbr.scanner.html` to your application, modify it and specify the new file as the default UI with the API `defaultUIElementURL` - - ```javascript - Dynamsoft.DBR.BarcodeScanner.defaultUIElementURL = url; - ``` - - *Note* - - You must set `defaultUIElementURL` before you call `createInstance`. - -* Build the UI element into your own web page and call `scanner.setUIElement(HTMLElement)` to specify that element. -* Append the default UI element to an element on your page. After that, you can customize it further. The following shows how to append the default UI to a DIV and hide the close button. - - ```html -
- ``` - - ```javascript - document.getElementById('scannerUI').appendChild(scanner.getUIElement()); - document.getElementsByClassName('dbrScanner-btn-close')[0].hidden = true; - ``` - -The following is an example of the 3rd option above. - -```html - - - -
- -
- - - - - -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/2jzeq1r6/) - -*NOTE* - -The video element must contain the class `dbrScanner-video` so that it can be used. - -```html - -``` - -### Cameras and Resolution Options - -Next, you can add the camera list and resolution list inside the UI element. In our case, the element would be `document.getElementById('div-video-container')`. - -If the class names match the default ones, `dbrScanner-sel-camera` and `dbrScanner-sel-resolution`, the library will automatically populate the lists and handle the camera/resolution switching automatically. - -```html - -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/nbj75vxu/) - -```html - -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/25v08paf/) - -*Note* - -By default, 8 hard-coded resolutions will be populated as options. - -The following code shows how to display a custom set of resolution options. - -```html - -``` - -*NOTE* - -Generally, you need to provide a resolution that the camera supports. However, in case a camera does not support the specified resolution, it usually uses the nearest supported resolution. As a result, the selected resolution may not be the actual resolution used. In this case, add an option with the class name `dbrScanner-opt-gotResolution` (as shown above) and the library will then use it to show the actual resolution. - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/tnfjks4q/) - -## Decode Barcodes from Existing Video Stream - -In v8.0, we introduced a new feature to decode barcodes from an existing video stream. To set the existing video stream, we'll use [setUIElement()](../api-reference/BarcodeScanner/methods/initialize-and-destroy.md#setuielement). - -```html - - - -
- -
- - - - - -``` -*NOTE* - -The video element must contain the class `dbrScanner-existingVideo`. diff --git a/programming-old/javascript/user-guide/basic-customizations.md b/programming-old/javascript/user-guide/basic-customizations.md deleted file mode 100644 index 669c5e0c..00000000 --- a/programming-old/javascript/user-guide/basic-customizations.md +++ /dev/null @@ -1,237 +0,0 @@ ---- -layout: default-layout -title: Basic Customizations - Dynamsoft Barcode Reader JavaScript Edition -description: This page shows how to customize basic features of Dynamsoft Barcode Reader JavaScript SDK. -keywords: user guide, basic customizations, initialize, javascript, js -needAutoGenerateSidebar: true -permalink: /programming/javascript/user-guide/basic-customizations.html ---- - -# Basic Customizations - -## Initialization - -The library is based on the `WebAssembly` standard; therefore, **on first use**, it needs some time to download and compile the `wasm` files. After first use, the browser may cache the file. - -`Dynamsoft.DBR.BarcodeReader.loadWasm()` is the API to start the initialization. - -```javascript -try{ - await Dynamsoft.DBR.BarcodeReader.loadWasm(); -}catch(ex){ - console.error(ex); -} -``` - -Other APIs like `Dynamsoft.DBR.BarcodeReader.createInstance()` and `Dynamsoft.DBR.BarcodeScanner.createInstance()` will also call `loadWasm()` during initialization. The following demonstrates the most common usage. - -```javascript -let reader = null; -let scanner = null; -try{ - reader = await Dynamsoft.DBR.BarcodeReader.createInstance(); - scanner = await Dynamsoft.DBR.BarcodeScanner.createInstance(); -}catch(ex){ - console.error(ex); -} -``` - -*NOTE* - -Including the library with a script tag doesn't automatically initialize the library. For better performance, you may want to call `loadWasm()` to download and compile the wasm file in advance and create a reader or scanner instance later. - -Initialization consists of the following steps: - -* Download - -Download the necessary resources. Usually, we deploy the resources on CDN and set a long cache duration. *If your web server is faster, you should put the resources on your own server instead of using the CDN.* - -* Compile - -The `wasm` files are automatically compiled once downloaded. The compilation time varies among different devices & browsers. While it takes less than a second on latest phones or PCs, it may take much longer on older devices. - -* Initialize - -The library needs to initialize every time the page loads. The initialization means creating a `BarcodeReader` or `BarcodeScanner` instance with specified settings. - -## Configuring Scanner Settings - -When creating an instance of the `BarcodeScanner` object, there are several configuration options. The following code shows some of the most popular ones: - -```javascript -// set which camera and what resolution to use -await scanner.updateVideoSettings({ video: { width: 1280, height: 720, facingMode: "environment" } }); - -// use one of the built-in RuntimeSetting templates: "single" (decode single barcode, default mode), "speed", "balance", "coverage". "speed" is recommended for decoding from a video stream -await scanner.updateRuntimeSettings("speed"); - -// make changes to the template. The code snippet below demonstrates how to specify which symbologies are enabled -let runtimeSettings = await scanner.getRuntimeSettings(); -runtimeSettings.barcodeFormatIds = Dynamsoft.EnumBarcodeFormat.BF_ONED | Dynamsoft.EnumBarcodeFormat.BF_QR_CODE; -await scanner.updateRuntimeSettings(runtimeSettings); - -// set up the scanner behavior -let scanSettings = await scanner.getScanSettings(); -// disregard duplicated results found in a specified time period -scanSettings.duplicateForgetTime = 20000; -// set a scan interval so the library may release the CPU from time to time -scanSettings.intervalTime = 300; -await scanner.updateScanSettings(scanSettings); -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/yfkcajxz/) - -As you can see in the code, there are three types of configurations: - -- `get/updateVideoSettings`: Configures the data source, i.e., the video stream. These settings include which camera to use, the resolution, etc. Learn more [here](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia#Syntax). - -- `get/updateRuntimeSettings`: Configures the decode engine. Find a full list of these settings and their corresponding descriptions [here](../api-reference/global-interfaces.md#runtimesettings). For example, the following uses the built-in "speed" settings with updated `localizationModes`. - - ```javascript - await barcodeScanner.updateRuntimeSettings("speed"); - //await barcodeScanner.updateRuntimeSettings("balance"); //alternative - //await barcodeScanner.updateRuntimeSettings("coverage"); //alternative - let settings = await barcodeScanner.getRuntimeSettings(); - settings.localizationModes = [ - Dynamsoft.EnumLocalizationMode.LM_CONNECTED_BLOCKS, - Dynamsoft.EnumLocalizationMode.LM_SCAN_DIRECTLY, - Dynamsoft.EnumLocalizationMode.LM_LINES, 0, 0, 0, 0, 0]; - await barcodeScanner.updateRuntimeSettings(settings); - ``` - Try in [JSFiddle](https://jsfiddle.net/DynamsoftTeam/f24h8c1m/). - -- `get/updateScanSettings`: Configures the behavior of the scanner which includes `duplicateForgetTime`, `intervalTime` and `filter`, etc. - -## Customizing the UI - -The library provides a built-in UI for the `BarcodeScanner`object where the default scanner UI is defined in the file `dist/dbr.scanner.html`. There are a few ways to customize it: - -* Modify the file `dist/dbr.scanner.html` directly. - - This option is only possible when you deploy these files yourself instead of using the CDN. - -* Copy the file `dist/dbr.scanner.html` to your application, modify it and specify the new file as the default UI with the API `defaultUIElementURL` - - ```javascript - Dynamsoft.DBR.BarcodeScanner.defaultUIElementURL = url; - ``` - - *Note* - - You must set `defaultUIElementURL` before you call `createInstance`. - -* Build the UI element into your own web page and call `scanner.setUIElement(HTMLElement)` to specify that element. -* Append the default UI element to an element on your page. After that, you can customize it further. The following shows how to append the default UI to a DIV and hide the close button. - - ```html -
- ``` - - ```javascript - document.getElementById('scannerUI').appendChild(scanner.getUIElement()); - document.getElementsByClassName('dbrScanner-btn-close')[0].hidden = true; - ``` - -The following is an example of the 3rd option above. - -```html - - - -
- -
- - - - - -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/2jzeq1r6/) - -*NOTE* - -The video element must contain the class `dbrScanner-video` so that it can be used. - -```html - -``` - -### Cameras and Resolution Options - -Next, you can add the camera list and resolution list inside the UI element. In our case, the element would be `document.getElementById('div-video-container')`. - -If the class names match the default ones, `dbrScanner-sel-camera` and `dbrScanner-sel-resolution`, the library will automatically populate the lists and handle the camera/resolution switching automatically. - -```html - -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/nbj75vxu/) - -```html - -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/25v08paf/) - -*Note* - -By default, 8 hard-coded resolutions will be populated as options. - -The following code shows how to display a custom set of resolution options. - -```html - -``` - -*NOTE* - -Generally, you need to provide a resolution that the camera supports. However, in case a camera does not support the specified resolution, it usually uses the nearest supported resolution. As a result, the selected resolution may not be the actual resolution used. In this case, add an option with the class name `dbrScanner-opt-gotResolution` (as shown above) and the library will then use it to show the actual resolution. - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/tnfjks4q/) - -## Decode Barcodes from Existing Video Stream - -In v8.0, we introduced a new feature to decode barcodes from an existing video stream. To set the existing video stream, we'll use [setUIElement()](../api-reference/BarcodeScanner/methods/initialize-and-destroy.md#setuielement). -s -```html - - - -
- -
- - - - - -``` -*NOTE* - -The video element must contain the class `dbrScanner-existingVideo`. diff --git a/programming-old/javascript/user-guide/default.md b/programming-old/javascript/user-guide/default.md deleted file mode 100644 index bb4f2db9..00000000 --- a/programming-old/javascript/user-guide/default.md +++ /dev/null @@ -1,21 +0,0 @@ ---- -layout: default-layout -title: User Guide - Dynamsoft Barcode Reader JavaScript Edition -description: This is the user guide index page of Dynamsoft Barcode Reader JavaScript SDK. -keywords: user guide index, javascript, js -breadcrumbText: User Guide Index -noTitleIndex: true -needGenerateH3Content: true -needAutoGenerateSidebar: true -permalink: /programming/javascript/user-guide/default.html ---- - -# DBR JavaScript Edition User Guide - -These articles will help you get the most out of Dynamsoft Barcode Reader JavaScript Edition. - -* If you have just started evaluating the SDK, read the [Get Started Guide](index-v9.6.42.md). - -* If you want to explore the many features of the SDK and make the most of it, read the articles in [Explore Features](explore-features/index.md). - -* If you want to check how the SDK works in popular use cases, read the articles in [Use Cases](use-cases/index.md). \ No newline at end of file diff --git a/programming-old/javascript/user-guide/deployment-activation-v7.5.0.md b/programming-old/javascript/user-guide/deployment-activation-v7.5.0.md deleted file mode 100644 index d083bbe9..00000000 --- a/programming-old/javascript/user-guide/deployment-activation-v7.5.0.md +++ /dev/null @@ -1,76 +0,0 @@ ---- -layout: default-layout -title: v7.5.0 Deployment - Dynamsoft Barcode Reader JavaScript Edition -description: This page shows how to deploy Dynamsoft Barcode Reader JavaScript SDK on your own server. -keywords: user guide, deployment, javascript, js -needAutoGenerateSidebar: true -permalink: /programming/javascript/user-guide/deployment-activation-v7.5.0.html ---- - -# Deployment Activation - -## Deployment: Self-hosted, Offline, or Intranet - -The following steps guide you through how to deploy the library on your own server. - -### Step One: Deploy the dist folder - -Locate the **dist/** directory under the installation folder of the library and simply copy the entire directory to your server. The **dist/** folder should contain the following files: - -- `dbr.js` // For ` -``` - -In the above sample code, simply replace `PRODUCT-KEYS` with your activated key. diff --git a/programming-old/javascript/user-guide/deployment-activation-v7.6.0.md b/programming-old/javascript/user-guide/deployment-activation-v7.6.0.md deleted file mode 100644 index b817f733..00000000 --- a/programming-old/javascript/user-guide/deployment-activation-v7.6.0.md +++ /dev/null @@ -1,76 +0,0 @@ ---- -layout: default-layout -title: v7.6.0 Deployment - Dynamsoft Barcode Reader JavaScript Edition -description: This page shows how to deploy Dynamsoft Barcode Reader JavaScript SDK on your own server. -keywords: user guide, deployment, javascript, js -needAutoGenerateSidebar: true -permalink: /programming/javascript/user-guide/deployment-activation-v7.6.0.html ---- - -# Deployment Activation - -## Deployment: Self-hosted, Offline, or Intranet - -The following steps guide you through how to deploy the library on your own server. - -### Step One: Deploy the dist folder - -Locate the **dist/** directory under the installation folder of the library and simply copy the entire directory to your server. The **dist/** folder should contain the following files: - -- `dbr.js` // For ` -``` - -In the above sample code, simply replace `PRODUCT-KEYS` with your activated key. diff --git a/programming-old/javascript/user-guide/deployment-activation.md b/programming-old/javascript/user-guide/deployment-activation.md deleted file mode 100644 index f387a8dc..00000000 --- a/programming-old/javascript/user-guide/deployment-activation.md +++ /dev/null @@ -1,56 +0,0 @@ ---- -layout: default-layout -title: Deployment - Dynamsoft Barcode Reader JavaScript Edition -description: This page shows how to deploy Dynamsoft Barcode Reader JavaScript SDK on your own server. -keywords: user guide, deployment, javascript, js -needAutoGenerateSidebar: true -permalink: /programming/javascript/user-guide/deployment-activation.html ---- - -# Deployment and Activation - -## Deployment: Self-hosted, Offline, or Intranet - -The following steps guide you through how to deploy the library on your own server instead of using it via a CDN. If you just want to use it over CDN, check out [one-minute set-up]({{site.js }}user-guide/?ver=latest#step-one-write-the-code-in-one-minute). - -### Step One: Deploy the dist folder - -Locate the "dist/" directory under the installation folder of the library and copy the entire directory to your server. - -"dist/" folder should contain the following files and more: - -- `dbr.js` // For referencing the library with a ` - - - -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/pL4e7yrd/) - - -`onFrameRead`: This event is triggered after each single frame is scanned. The `results` object contains all the barcode results that the library found on this frame. In this example, we will print the results found in every frame to the console. - -`onUnduplicatedRead`: This event is triggered when a new barcode (not a duplicate) is found. `txt` holds the barcode text value while `result` is an object that holds details of the found barcode. In this example, an alert will be displayed for each unique barcode found. - - -### Step Two: Enable camera access - -Open the HTML page in your browser and you should see a pop-up asking for permission to access the camera. Once camera access is granted, the video stream will start in the default UI of the **BarcodeScanner** object. - -**Note**: If you don't see the pop-up, wait a few seconds for the initialization to finish. - -In this step, you might run into the following issues: - -#### getUserMedia non-HTTPS access issue - -If you open the HTML file as `file:///` or `http://`, the following error may appear in 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 equivalent error is: - -> Trying to call getUserMedia from an insecure document. - -To access the camera with the API [getUserMedia](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia), HTTPS is required. - -**Note**: If you use Chrome or Firefox, you might not get the error because these two browsers allow camera access via file:/// and http://localhost. - -To make sure your web application can access the camera, please configure your web server to support HTTPS. The following links may help. - -- NGINX: [Configuring HTTPS servers](https://nginx.org/en/docs/http/configuring_https_servers.html) -- IIS: [Create a Self Signed Certificate in IIS](https://aboutssl.org/how-to-create-a-self-signed-certificate-in-iis/) -- Tomcat: [Setting Up SSL on Tomcat in 5 minutes](https://dzone.com/articles/setting-ssl-tomcat-5-minutes) -- Node.js: [npm tls](https://nodejs.org/docs/v0.4.1/api/tls.html) - -#### Self-signed certificate issue - -For testing purposes, a self-signed certificate can be used when configuring HTTPS. When accessing the site, the browser might say "the site is not secure". In this case, go to the certificate settings and set to trust this certificate. - -In a production environment, you will need a valid HTTPS certificate. - -### Step Three: Time to scan - -Place a barcode in front of the camera. You should see an alert pop up with the decoded barcode result and a coloured region on the video to highlight the barcode location. - -## Installation - -yarn - -``` -$ yarn add dynamsoft-javascript-barcode -``` - -npm - -``` -$ npm install dynamsoft-javascript-barcode --save -``` - -cdn - -``` - - - -``` - -Also see [Dynamsoft JavaScript Barcode SDK for Node](https://github.com/dynamsoft-dbr/node-javascript-barcode). - - -## Demos and Examples - -- [Online demo](https://demo.dynamsoft.com/dbr_wasm/barcode_reader_javascript.html) -- [Vue example](https://github.com/Dynamsoft/javascript-barcode/tree/master/example/web/vue) -- [React example](https://github.com/Dynamsoft/javascript-barcode/tree/master/example/web/react) -- [Angular example](https://github.com/Dynamsoft/javascript-barcode/tree/master/example/web/angular) - diff --git a/programming-old/javascript/user-guide/index-v7.6.0.md b/programming-old/javascript/user-guide/index-v7.6.0.md deleted file mode 100644 index f64518c8..00000000 --- a/programming-old/javascript/user-guide/index-v7.6.0.md +++ /dev/null @@ -1,143 +0,0 @@ ---- -layout: default-layout -title: v7.6.0 User Guide - Dynamsoft Barcode Reader JavaScript Edition -description: This is the user guide of Dynamsoft Barcode Reader JavaScript SDK. -keywords: user guide, javascript, js -breadcrumbText: User Guide -needAutoGenerateSidebar: false -permalink: /programming/javascript/user-guide/index-v7.6.0.html ---- - -# Dynamsoft Barcode Reader JavaScript Edition - User Guide - -![Dynamsoft JavaScript Barcode SDK](assets/dbr-js-sdk.png) - -[Dynamsoft BarcodeReader SDK for Web](https://www.dynamsoft.com/Products/barcode-recognition-javascript.aspx) is a JavaScript SDK for barcode scanning based on **WebAssembly**. It supports real-time barcode localization and decoding of various barcode types. The library is capable of scanning barcodes directly from live video streams and static images. It also supports reading multiple barcodes at once. - -In this guide, you will learn step by step how to use Dynamsoft Barcode Reader JavaScript Edition in your application: - -- [Getting Started](#getting-started---hello-world) -- [Installation](#installation) -- [Basic Customizations]({{ site.js }}user-guide/basic-customizations.html) -- [Advanced Customizations]({{ site.js }}user-guide/advanced-customizations.html) -- [Deployment Activation]({{ site.js }}user-guide/deployment-activation.html) -- [Features Requirements]({{ site.js }}user-guide/features-requirements.html) -- [Upgrade]({{ site.js }}user-guide/upgrade.html) - - -## Getting Started - Hello World - -Let's start by using the library to build a simple web application that will decode barcodes from a live video stream. - -### Basic Requirements - -- Internet connection -- Supported Browser -- Camera access - -### Step One: Write the code in one minute - -Create an HTML file with the following content. Deploy this to your web server and run the application over **HTTPS**. - -- You will need to replace `PRODUCT-KEYS` with a trial key for the sample code to work correctly. You can acquire a trial key [here](https://www.dynamsoft.com/customer/license/trialLicense?utm_source=guide&product=dbr&package=js). -- If you don't have a ready-to-use web server but have a package manager like npm or yarn, you can set up a simple HTTP server in minutes. Check out `http-server` on npm or yarn. - -```html - - - - - - - - -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/pL4e7yrd/) - - -`onFrameRead`: This event is triggered after each single frame is scanned. The `results` object contains all the barcode results that the library found on this frame. In this example, we will print the results found in every frame to the console. - -`onUnduplicatedRead`: This event is triggered when a new barcode (not a duplicate) is found. `txt` holds the barcode text value while `result` is an object that holds details of the found barcode. In this example, an alert will be displayed for each unique barcode found. - - -### Step Two: Enable camera access - -Open the HTML page in your browser and you should see a pop-up asking for permission to access the camera. Once camera access is granted, the video stream will start in the default UI of the **BarcodeScanner** object. - -**Note**: If you don't see the pop-up, wait a few seconds for the initialization to finish. - -In this step, you might run into the following issues: - -#### getUserMedia non-HTTPS access issue - -If you open the HTML file as `file:///` or `http://`, the following error may appear in 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 equivalent error is: - -> Trying to call getUserMedia from an insecure document. - -To access the camera with the API [getUserMedia](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia), HTTPS is required. - -**Note**: If you use Chrome or Firefox, you might not get the error because these two browsers allow camera access via file:/// and http://localhost. - -To make sure your web application can access the camera, please configure your web server to support HTTPS. The following links may help. - -- NGINX: [Configuring HTTPS servers](https://nginx.org/en/docs/http/configuring_https_servers.html) -- IIS: [Create a Self Signed Certificate in IIS](https://aboutssl.org/how-to-create-a-self-signed-certificate-in-iis/) -- Tomcat: [Setting Up SSL on Tomcat in 5 minutes](https://dzone.com/articles/setting-ssl-tomcat-5-minutes) -- Node.js: [npm tls](https://nodejs.org/docs/v0.4.1/api/tls.html) - -#### Self-signed certificate issue - -For testing purposes, a self-signed certificate can be used when configuring HTTPS. When accessing the site, the browser might say "the site is not secure". In this case, go to the certificate settings and set to trust this certificate. - -In a production environment, you will need a valid HTTPS certificate. - -### Step Three: Time to scan - -Place a barcode in front of the camera. You should see an alert pop up with the decoded barcode result and a coloured region on the video to highlight the barcode location. - -## Installation - -yarn - -``` -$ yarn add dynamsoft-javascript-barcode -``` - -npm - -``` -$ npm install dynamsoft-javascript-barcode --save -``` - -cdn - -``` - - - -``` - -Also see [Dynamsoft JavaScript Barcode SDK for Node](https://github.com/dynamsoft-dbr/node-javascript-barcode). - - -## Demos and Examples - -- [Online demo](https://demo.dynamsoft.com/dbr_wasm/barcode_reader_javascript.html) -- [Vue example](https://github.com/Dynamsoft/javascript-barcode/tree/master/example/web/vue) -- [React example](https://github.com/Dynamsoft/javascript-barcode/tree/master/example/web/react) -- [Angular example](https://github.com/Dynamsoft/javascript-barcode/tree/master/example/web/angular) - diff --git a/programming-old/javascript/user-guide/index-v8.0.0.md b/programming-old/javascript/user-guide/index-v8.0.0.md deleted file mode 100644 index 7eb70602..00000000 --- a/programming-old/javascript/user-guide/index-v8.0.0.md +++ /dev/null @@ -1,143 +0,0 @@ ---- -layout: default-layout -title: v8.0.0 User Guide - Dynamsoft Barcode Reader JavaScript Edition -description: This is the user guide of Dynamsoft Barcode Reader JavaScript SDK. -keywords: user guide, javascript, js -breadcrumbText: User Guide -needAutoGenerateSidebar: false -permalink: /programming/javascript/user-guide/index-v8.0.0.html ---- - -# Dynamsoft Barcode Reader JavaScript Edition - User Guide - -![Dynamsoft JavaScript Barcode SDK](assets/dbr-js-sdk.png) - -[Dynamsoft BarcodeReader SDK for Web](https://www.dynamsoft.com/Products/barcode-recognition-javascript.aspx) is a JavaScript SDK for barcode scanning based on **WebAssembly**. It supports real-time barcode localization and decoding of various barcode types. The library is capable of scanning barcodes directly from live video streams and static images. It also supports reading multiple barcodes at once. - -In this guide, you will learn step by step how to use Dynamsoft Barcode Reader JavaScript Edition in your application: - -- [Getting Started](#getting-started---hello-world) -- [Installation](#installation) -- [Basic Customizations]({{ site.js }}user-guide/basic-customizations.html) -- [Advanced Customizations]({{ site.js }}user-guide/advanced-customizations.html) -- [Deployment Activation]({{ site.js }}user-guide/deployment-activation.html) -- [Features Requirements]({{ site.js }}user-guide/features-requirements.html) -- [Upgrade]({{ site.js }}user-guide/upgrade.html) - - -## Getting Started - Hello World - -Let's start by using the library to build a simple web application that will decode barcodes from a live video stream. - -### Basic Requirements - -- Internet connection -- Supported Browser -- Camera access - -### Step One: Write the code in one minute - -Create an HTML file with the following content. Deploy this to your web server and run the application over **HTTPS**. - -- You will need to replace `PRODUCT-KEYS` with a trial key for the sample code to work correctly. You can acquire a trial key [here](https://www.dynamsoft.com/customer/license/trialLicense?utm_source=guide&product=dbr&package=js). -- If you don't have a ready-to-use web server but have a package manager like npm or yarn, you can set up a simple HTTP server in minutes. Check out `http-server` on npm or yarn. - -```html - - - - - - - - -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/pL4e7yrd/) - - -`onFrameRead`: This event is triggered after each single frame is scanned. The `results` object contains all the barcode results that the library found on this frame. In this example, we will print the results found in every frame to the console. - -`onUnduplicatedRead`: This event is triggered when a new barcode (not a duplicate) is found. `txt` holds the barcode text value while `result` is an object that holds details of the found barcode. In this example, an alert will be displayed for each unique barcode found. - - -### Step Two: Enable camera access - -Open the HTML page in your browser and you should see a pop-up asking for permission to access the camera. Once camera access is granted, the video stream will start in the default UI of the **BarcodeScanner** object. - -**Note**: If you don't see the pop-up, wait a few seconds for the initialization to finish. - -In this step, you might run into the following issues: - -#### getUserMedia non-HTTPS access issue - -If you open the HTML file as `file:///` or `http://`, the following error may appear in 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 equivalent error is: - -> Trying to call getUserMedia from an insecure document. - -To access the camera with the API [getUserMedia](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia), HTTPS is required. - -**Note**: If you use Chrome or Firefox, you might not get the error because these two browsers allow camera access via file:/// and http://localhost. - -To make sure your web application can access the camera, please configure your web server to support HTTPS. The following links may help. - -- NGINX: [Configuring HTTPS servers](https://nginx.org/en/docs/http/configuring_https_servers.html) -- IIS: [Create a Self Signed Certificate in IIS](https://aboutssl.org/how-to-create-a-self-signed-certificate-in-iis/) -- Tomcat: [Setting Up SSL on Tomcat in 5 minutes](https://dzone.com/articles/setting-ssl-tomcat-5-minutes) -- Node.js: [npm tls](https://nodejs.org/docs/v0.4.1/api/tls.html) - -#### Self-signed certificate issue - -For testing purposes, a self-signed certificate can be used when configuring HTTPS. When accessing the site, the browser might say "the site is not secure". In this case, go to the certificate settings and set to trust this certificate. - -In a production environment, you will need a valid HTTPS certificate. - -### Step Three: Time to scan - -Place a barcode in front of the camera. You should see an alert pop up with the decoded barcode result and a coloured region on the video to highlight the barcode location. - -## Installation - -yarn - -``` -$ yarn add dynamsoft-javascript-barcode -``` - -npm - -``` -$ npm install dynamsoft-javascript-barcode --save -``` - -cdn - -``` - - - -``` - -Also see [Dynamsoft JavaScript Barcode SDK for Node](https://github.com/dynamsoft-dbr/node-javascript-barcode). - - -## Demos and Examples - -- [Online demo](https://demo.dynamsoft.com/dbr_wasm/barcode_reader_javascript.html) -- [Vue example](https://github.com/Dynamsoft/javascript-barcode/tree/master/example/web/vue) -- [React example](https://github.com/Dynamsoft/javascript-barcode/tree/master/example/web/react) -- [Angular example](https://github.com/Dynamsoft/javascript-barcode/tree/master/example/web/angular) - diff --git a/programming-old/javascript/user-guide/index-v8.1.0.md b/programming-old/javascript/user-guide/index-v8.1.0.md deleted file mode 100644 index a1e34a32..00000000 --- a/programming-old/javascript/user-guide/index-v8.1.0.md +++ /dev/null @@ -1,143 +0,0 @@ ---- -layout: default-layout -title: v8.1.0 User Guide - Dynamsoft Barcode Reader JavaScript Edition -description: This is the user guide of Dynamsoft Barcode Reader JavaScript SDK. -keywords: user guide, javascript, js -breadcrumbText: User Guide -needAutoGenerateSidebar: false -permalink: /programming/javascript/user-guide/index-v8.1.0.html ---- - -# Dynamsoft Barcode Reader JavaScript Edition - User Guide - -![Dynamsoft JavaScript Barcode SDK](assets/dbr-js-sdk.png) - -[Dynamsoft BarcodeReader SDK for Web](https://www.dynamsoft.com/Products/barcode-recognition-javascript.aspx) is a JavaScript SDK for barcode scanning based on **WebAssembly**. It supports real-time barcode localization and decoding of various barcode types. The library is capable of scanning barcodes directly from live video streams and static images. It also supports reading multiple barcodes at once. - -In this guide, you will learn step by step how to use Dynamsoft Barcode Reader JavaScript Edition in your application: - -- [Getting Started](#getting-started---hello-world) -- [Installation](#installation) -- [Basic Customizations]({{ site.js }}user-guide/basic-customizations.html) -- [Advanced Customizations]({{ site.js }}user-guide/advanced-customizations.html) -- [Deployment Activation]({{ site.js }}user-guide/deployment-activation.html) -- [Features Requirements]({{ site.js }}user-guide/features-requirements.html) -- [Upgrade]({{ site.js }}user-guide/upgrade.html) - - -## Getting Started - Hello World - -Let's start by using the library to build a simple web application that will decode barcodes from a live video stream. - -### Basic Requirements - -- Internet connection -- Supported Browser -- Camera access - -### Step One: Write the code in one minute - -Create an HTML file with the following content. Deploy this to your web server and run the application over **HTTPS**. - -- You will need to replace `PRODUCT-KEYS` with a trial key for the sample code to work correctly. You can acquire a trial key [here](https://www.dynamsoft.com/customer/license/trialLicense?utm_source=guide&product=dbr&package=js). -- If you don't have a ready-to-use web server but have a package manager like npm or yarn, you can set up a simple HTTP server in minutes. Check out `http-server` on npm or yarn. - -```html - - - - - - - - -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/pL4e7yrd/) - - -`onFrameRead`: This event is triggered after each single frame is scanned. The `results` object contains all the barcode results that the library found on this frame. In this example, we will print the results found in every frame to the console. - -`onUnduplicatedRead`: This event is triggered when a new barcode (not a duplicate) is found. `txt` holds the barcode text value while `result` is an object that holds details of the found barcode. In this example, an alert will be displayed for each unique barcode found. - - -### Step Two: Enable camera access - -Open the HTML page in your browser and you should see a pop-up asking for permission to access the camera. Once camera access is granted, the video stream will start in the default UI of the **BarcodeScanner** object. - -**Note**: If you don't see the pop-up, wait a few seconds for the initialization to finish. - -In this step, you might run into the following issues: - -#### getUserMedia non-HTTPS access issue - -If you open the HTML file as `file:///` or `http://`, the following error may appear in 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 equivalent error is: - -> Trying to call getUserMedia from an insecure document. - -To access the camera with the API [getUserMedia](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia), HTTPS is required. - -**Note**: If you use Chrome or Firefox, you might not get the error because these two browsers allow camera access via file:/// and http://localhost. - -To make sure your web application can access the camera, please configure your web server to support HTTPS. The following links may help. - -- NGINX: [Configuring HTTPS servers](https://nginx.org/en/docs/http/configuring_https_servers.html) -- IIS: [Create a Self Signed Certificate in IIS](https://aboutssl.org/how-to-create-a-self-signed-certificate-in-iis/) -- Tomcat: [Setting Up SSL on Tomcat in 5 minutes](https://dzone.com/articles/setting-ssl-tomcat-5-minutes) -- Node.js: [npm tls](https://nodejs.org/docs/v0.4.1/api/tls.html) - -#### Self-signed certificate issue - -For testing purposes, a self-signed certificate can be used when configuring HTTPS. When accessing the site, the browser might say "the site is not secure". In this case, go to the certificate settings and set to trust this certificate. - -In a production environment, you will need a valid HTTPS certificate. - -### Step Three: Time to scan - -Place a barcode in front of the camera. You should see an alert pop up with the decoded barcode result and a coloured region on the video to highlight the barcode location. - -## Installation - -yarn - -``` -$ yarn add dynamsoft-javascript-barcode -``` - -npm - -``` -$ npm install dynamsoft-javascript-barcode --save -``` - -cdn - -``` - - - -``` - -Also see [Dynamsoft JavaScript Barcode SDK for Node](https://github.com/dynamsoft-dbr/node-javascript-barcode). - - -## Demos and Examples - -- [Online demo](https://demo.dynamsoft.com/dbr_wasm/barcode_reader_javascript.html) -- [Vue example](https://github.com/Dynamsoft/javascript-barcode/tree/master/example/web/vue) -- [React example](https://github.com/Dynamsoft/javascript-barcode/tree/master/example/web/react) -- [Angular example](https://github.com/Dynamsoft/javascript-barcode/tree/master/example/web/angular) - diff --git a/programming-old/javascript/user-guide/index-v8.1.2.md b/programming-old/javascript/user-guide/index-v8.1.2.md deleted file mode 100644 index 98125771..00000000 --- a/programming-old/javascript/user-guide/index-v8.1.2.md +++ /dev/null @@ -1,162 +0,0 @@ ---- -layout: default-layout -title: v8.1.2 User Guide - Dynamsoft Barcode Reader JavaScript Edition -description: This is the user guide of Dynamsoft Barcode Reader JavaScript SDK. -keywords: user guide, javascript, js -breadcrumbText: User Guide -needAutoGenerateSidebar: true -permalink: /programming/javascript/user-guide/index-v8.1.2.html ---- - -# Dynamsoft Barcode Reader JavaScript Edition - User Guide - -![Dynamsoft JavaScript Barcode SDK](assets/dbr-js-sdk.png) - -[Dynamsoft BarcodeReader SDK for Web](https://www.dynamsoft.com/Products/barcode-recognition-javascript.aspx) is a JavaScript SDK for barcode scanning based on **WebAssembly**. It supports real-time barcode localization and decoding of various barcode types. The library is capable of scanning barcodes directly from live video streams as well as static images. It also supports reading multiple barcodes at once. - -In this guide, you will learn step by step how to use Dynamsoft Barcode Reader JavaScript Edition in your application: - -- [Getting Started](#getting-started---hello-world) -- [Installation](#installation) -- [Basic Customizations]({{ site.js }}user-guide/basic-customizations.html) -- [Advanced Customizations]({{ site.js }}user-guide/advanced-customizations.html) -- [Deployment Activation]({{ site.js }}user-guide/deployment-activation.html) -- [Features Requirements]({{ site.js }}user-guide/features-requirements.html) -- [Upgrade]({{ site.js }}user-guide/upgrade.html) - - -## Getting Started - Hello World - -Let's start by using the library to build a simple web application that will decode barcodes from a live video stream. - -### Basic Requirements - -- Internet connection -- [Supported Browser]({{site.js}}user-guide/features-requirements.html#system-requirements) -- Camera access - -### Step One: Write the code in one minute - -Creat a text file anywhere on your local disk and name it "helloworld.html". Copy the following content in the file and save. - -```html - - - - - - - - -``` - -*About the code* - -- `onFrameRead`: This event is triggered after the library finishes scanning a frame from the video stream. The `results` object contains all the barcode results that the library found on this frame. In this example, we print the results to the browser console. - -- `onUnduplicatedRead`: This event is triggered when a new barcode (not a duplicate) is found. `txt` holds the barcode text value while `result` is an object that holds details of the barcode. In this example, an alert will be displayed for each unique barcode found. Notice that if the same barcode is found on multiple consecutive frames, this event is only triggered once. - - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/pL4e7yrd/) - -*Note*: - -- The recommendation is to deploy this page to your web server and run it over **HTTPS**. If you don't have a ready-to-use web server but have a package manager like npm or yarn, you can set up a simple HTTP server in minutes. Check out [http-server on npm](https://www.npmjs.com/package/http-server) or [yarn](https://yarnpkg.com/package/http-server). However, for simple testing purposes, it's perfectly fine to just open the file directly from your local disk. - -- You will need to replace `PRODUCT-KEYS` with a trial key (or your Handshake Code if you have got one) for the sample code to work correctly. You can acquire a trial key [here](https://www.dynamsoft.com/customer/license/trialLicense?utm_source=guide&product=dbr&package=js). Notice that the library will still read barcodes without a valid key (Code), but will return an annotated result string. - -- The library only scans a new frame when it has finished scanning the previous frame. Generally, frames come in faster than the library processes a frame (for 30 FPS, the interval is about 33 ms), therefore not all frames are scanned. - -### Step Two: Enable camera access - -Open the HTML page in your browser and you should see a pop-up asking for permission to access the camera. Once the access is granted, the video stream will start in the default UI of the **BarcodeScanner** object. - -*Note*: - -- If you don't see the pop-up, wait a few seconds for the initialization to finish. - -In this step, you might run into the following issues: - -#### getUserMedia non-HTTPS access issue - -If you opened the HTML file as `file:///` or `http://`, the following error may appear in 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 equivalent error is: - -> Trying to call getUserMedia from an insecure document. - -You get this error because to access the camera with the API [getUserMedia](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia), HTTPS is required. - -*Note* - -- If you use Chrome or Firefox, you might not get the error because these two browsers allow camera access via file:/// and http://localhost. - -To make sure your web application can access the camera, please configure your web server to support HTTPS. The following links may help. - -- NGINX: [Configuring HTTPS servers](https://nginx.org/en/docs/http/configuring_https_servers.html) -- IIS: [Create a Self Signed Certificate in IIS](https://aboutssl.org/how-to-create-a-self-signed-certificate-in-iis/) -- Tomcat: [Setting Up SSL on Tomcat in 5 minutes](https://dzone.com/articles/setting-ssl-tomcat-5-minutes) -- Node.js: [npm tls](https://nodejs.org/docs/v0.4.1/api/tls.html) - -#### Self-signed certificate issue - -For testing purposes, a self-signed certificate can be used when configuring HTTPS. When accessing the site, the browser might say "the site is not secure". In this case, go to the certificate settings and trust this certificate. - -In a production environment, a valid HTTPS certificate is required. - -### Step Three: Time to scan - -Place a barcode in front of the camera. You should see an alert pop up with the decoded barcode result and a coloured region on the video to highlight the barcode location. - -## Installation - -For evaluation purposes, we recommend that you get the official package of the library for developers. The following shows how to acquire the package. - -* From the website - - [Download Dynamsoft Barcode Reader](https://www.dynamsoft.com/barcode-reader/downloads/) - -* yarn - - ``` - $ yarn add dynamsoft-javascript-barcode - ``` - -* npm - - ``` - $ npm install dynamsoft-javascript-barcode --save - ``` - -If you want to start building your application right away, you can also just make use of the library via CDN as shown in the previous helloworld sample code. - -* cdn - - ``` - - - - ``` - -Dynamsoft also provides a Barcode Reader SDK built for Node, see [Dynamsoft JavaScript Barcode SDK for Node](https://github.com/dynamsoft-dbr/node-javascript-barcode). - -## Demos and Examples - -The following are the official demo of the library and examples for the most popular JavaScript Frameworks. - -- [Online demo](https://demo.dynamsoft.com/barcode-reader-js/) -- [Vue example](https://github.com/Dynamsoft/javascript-barcode/tree/master/example/web/vue) -- [React example](https://github.com/Dynamsoft/javascript-barcode/tree/master/example/web/react) -- [Angular example](https://github.com/Dynamsoft/javascript-barcode/tree/master/example/web/angular) - diff --git a/programming-old/javascript/user-guide/index-v8.1.3.md b/programming-old/javascript/user-guide/index-v8.1.3.md deleted file mode 100644 index 855e900c..00000000 --- a/programming-old/javascript/user-guide/index-v8.1.3.md +++ /dev/null @@ -1,162 +0,0 @@ ---- -layout: default-layout -title: v8.1.3 User Guide - Dynamsoft Barcode Reader JavaScript Edition -description: This is the user guide of Dynamsoft Barcode Reader JavaScript SDK. -keywords: user guide, javascript, js -breadcrumbText: User Guide -needAutoGenerateSidebar: true -permalink: /programming/javascript/user-guide/index-v8.1.3.html ---- - -# Dynamsoft Barcode Reader JavaScript Edition - User Guide - -![Dynamsoft JavaScript Barcode SDK](assets/dbr-js-sdk.png) - -[Dynamsoft BarcodeReader SDK for Web](https://www.dynamsoft.com/Products/barcode-recognition-javascript.aspx) is a JavaScript SDK for barcode scanning based on **WebAssembly**. It supports real-time barcode localization and decoding of various barcode types. The library is capable of scanning barcodes directly from live video streams as well as static images. It also supports reading multiple barcodes at once. - -In this guide, you will learn step by step how to use Dynamsoft Barcode Reader JavaScript Edition in your application: - -- [Getting Started](#getting-started---hello-world) -- [Installation](#installation) -- [Basic Customizations]({{ site.js }}user-guide/basic-customizations.html) -- [Advanced Customizations]({{ site.js }}user-guide/advanced-customizations.html) -- [Deployment Activation]({{ site.js }}user-guide/deployment-activation.html) -- [Features Requirements]({{ site.js }}user-guide/features-requirements.html) -- [Upgrade]({{ site.js }}user-guide/upgrade.html) - - -## Getting Started - Hello World - -Let's start by using the library to build a simple web application that will decode barcodes from a live video stream. - -### Basic Requirements - -- Internet connection -- [Supported Browser]({{site.js}}user-guide/features-requirements.html#system-requirements) -- Camera access - -### Step One: Write the code in one minute - -Creat a text file anywhere on your local disk and name it "helloworld.html". Copy the following content in the file and save. - -```html - - - - - - - - -``` - -*About the code* - -- `onFrameRead`: This event is triggered after the library finishes scanning a frame from the video stream. The `results` object contains all the barcode results that the library found on this frame. In this example, we print the results to the browser console. - -- `onUnduplicatedRead`: This event is triggered when a new barcode (not a duplicate) is found. `txt` holds the barcode text value while `result` is an object that holds details of the barcode. In this example, an alert will be displayed for each unique barcode found. Notice that if the same barcode is found on multiple consecutive frames, this event is only triggered once. - - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/pL4e7yrd/) - -*Note*: - -- The recommendation is to deploy this page to your web server and run it over **HTTPS**. If you don't have a ready-to-use web server but have a package manager like npm or yarn, you can set up a simple HTTP server in minutes. Check out [http-server on npm](https://www.npmjs.com/package/http-server) or [yarn](https://yarnpkg.com/package/http-server). However, for simple testing purposes, it's perfectly fine to just open the file directly from your local disk. - -- You will need to replace `PRODUCT-KEYS` with a trial key (or your Handshake Code if you have got one) for the sample code to work correctly. You can acquire a trial key [here](https://www.dynamsoft.com/customer/license/trialLicense?utm_source=guide&product=dbr&package=js). Notice that the library will still read barcodes without a valid key (Code), but will return an annotated result string. - -- The library only scans a new frame when it has finished scanning the previous frame. Generally, frames come in faster than the library processes a frame (for 30 FPS, the interval is about 33 ms), therefore not all frames are scanned. - -### Step Two: Enable camera access - -Open the HTML page in your browser and you should see a pop-up asking for permission to access the camera. Once the access is granted, the video stream will start in the default UI of the **BarcodeScanner** object. - -*Note*: - -- If you don't see the pop-up, wait a few seconds for the initialization to finish. - -In this step, you might run into the following issues: - -#### getUserMedia non-HTTPS access issue - -If you opened the HTML file as `file:///` or `http://`, the following error may appear in 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 equivalent error is: - -> Trying to call getUserMedia from an insecure document. - -You get this error because to access the camera with the API [getUserMedia](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia), HTTPS is required. - -*Note* - -- If you use Chrome or Firefox, you might not get the error because these two browsers allow camera access via file:/// and http://localhost. - -To make sure your web application can access the camera, please configure your web server to support HTTPS. The following links may help. - -- NGINX: [Configuring HTTPS servers](https://nginx.org/en/docs/http/configuring_https_servers.html) -- IIS: [Create a Self Signed Certificate in IIS](https://aboutssl.org/how-to-create-a-self-signed-certificate-in-iis/) -- Tomcat: [Setting Up SSL on Tomcat in 5 minutes](https://dzone.com/articles/setting-ssl-tomcat-5-minutes) -- Node.js: [npm tls](https://nodejs.org/docs/v0.4.1/api/tls.html) - -#### Self-signed certificate issue - -For testing purposes, a self-signed certificate can be used when configuring HTTPS. When accessing the site, the browser might say "the site is not secure". In this case, go to the certificate settings and trust this certificate. - -In a production environment, a valid HTTPS certificate is required. - -### Step Three: Time to scan - -Place a barcode in front of the camera. You should see an alert pop up with the decoded barcode result and a coloured region on the video to highlight the barcode location. - -## Installation - -For evaluation purposes, we recommend that you get the official package of the library for developers. The following shows how to acquire the package. - -* From the website - - [Download Dynamsoft Barcode Reader](https://www.dynamsoft.com/barcode-reader/downloads/) - -* yarn - - ``` - $ yarn add dynamsoft-javascript-barcode - ``` - -* npm - - ``` - $ npm install dynamsoft-javascript-barcode --save - ``` - -If you want to start building your application right away, you can also just make use of the library via CDN as shown in the previous helloworld sample code. - -* cdn - - ``` - - - - ``` - -Dynamsoft also provides a Barcode Reader SDK built for Node, see [Dynamsoft JavaScript Barcode SDK for Node](https://github.com/dynamsoft-dbr/node-javascript-barcode). - -## Demos and Examples - -The following are the official demo of the library and examples for the most popular JavaScript Frameworks. - -- [Online demo](https://demo.dynamsoft.com/barcode-reader-js/) -- [Vue example](https://github.com/Dynamsoft/javascript-barcode/tree/master/example/web/vue) -- [React example](https://github.com/Dynamsoft/javascript-barcode/tree/master/example/web/react) -- [Angular example](https://github.com/Dynamsoft/javascript-barcode/tree/master/example/web/angular) - diff --git a/programming-old/javascript/user-guide/index-v8.2.0.md b/programming-old/javascript/user-guide/index-v8.2.0.md deleted file mode 100644 index 6e9bb4a0..00000000 --- a/programming-old/javascript/user-guide/index-v8.2.0.md +++ /dev/null @@ -1,162 +0,0 @@ ---- -layout: default-layout -title: v8.2.0 User Guide - Dynamsoft Barcode Reader JavaScript Edition -description: This is the user guide of Dynamsoft Barcode Reader JavaScript SDK. -keywords: user guide, javascript, js -breadcrumbText: User Guide -needAutoGenerateSidebar: true -permalink: /programming/javascript/user-guide/index-v8.2.0.html ---- - -# Dynamsoft Barcode Reader JavaScript Edition - User Guide - -![Dynamsoft JavaScript Barcode SDK](assets/dbr-js-sdk.png) - -[Dynamsoft BarcodeReader SDK for Web](https://www.dynamsoft.com/Products/barcode-recognition-javascript.aspx) is a JavaScript SDK for barcode scanning based on **WebAssembly**. It supports real-time barcode localization and decoding of various barcode types. The library is capable of scanning barcodes directly from live video streams as well as static images. It also supports reading multiple barcodes at once. - -In this guide, you will learn step by step how to use Dynamsoft Barcode Reader JavaScript Edition in your application: - -- [Getting Started](#getting-started---hello-world) -- [Installation](#installation) -- [Basic Customizations]({{ site.js }}user-guide/basic-customizations.html) -- [Advanced Customizations]({{ site.js }}user-guide/advanced-customizations.html) -- [Deployment Activation]({{ site.js }}user-guide/deployment-activation.html) -- [Features Requirements]({{ site.js }}user-guide/features-requirements.html) -- [Upgrade]({{ site.js }}user-guide/upgrade.html) - - -## Getting Started - Hello World - -Let's start by using the library to build a simple web application that will decode barcodes from a live video stream. - -### Basic Requirements - -- Internet connection -- [Supported Browser]({{site.js}}user-guide/features-requirements.html#system-requirements) -- Camera access - -### Step One: Write the code in one minute - -Creat a text file anywhere on your local disk and name it "helloworld.html". Copy the following content in the file and save. - -```html - - - - - - - - -``` - -*About the code* - -- `onFrameRead`: This event is triggered after the library finishes scanning a frame from the video stream. The `results` object contains all the barcode results that the library found on this frame. In this example, we print the results to the browser console. - -- `onUnduplicatedRead`: This event is triggered when a new barcode (not a duplicate) is found. `txt` holds the barcode text value while `result` is an object that holds details of the barcode. In this example, an alert will be displayed for each unique barcode found. Notice that if the same barcode is found on multiple consecutive frames, this event is only triggered once. - - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/pL4e7yrd/) - -*Note*: - -- The recommendation is to deploy this page to your web server and run it over **HTTPS**. If you don't have a ready-to-use web server but have a package manager like npm or yarn, you can set up a simple HTTP server in minutes. Check out [http-server on npm](https://www.npmjs.com/package/http-server) or [yarn](https://yarnpkg.com/package/http-server). However, for simple testing purposes, it's perfectly fine to just open the file directly from your local disk. - -- You will need to replace `PRODUCT-KEYS` with a trial key (or your Handshake Code if you have got one) for the sample code to work correctly. You can acquire a trial key [here](https://www.dynamsoft.com/customer/license/trialLicense?utm_source=guide&product=dbr&package=js). Notice that the library will still read barcodes without a valid key (Code), but will return an annotated result string. - -- The library only scans a new frame when it has finished scanning the previous frame. Generally, frames come in faster than the library processes a frame (for 30 FPS, the interval is about 33 ms), therefore not all frames are scanned. - -### Step Two: Enable camera access - -Open the HTML page in your browser and you should see a pop-up asking for permission to access the camera. Once the access is granted, the video stream will start in the default UI of the **BarcodeScanner** object. - -*Note*: - -- If you don't see the pop-up, wait a few seconds for the initialization to finish. - -In this step, you might run into the following issues: - -#### getUserMedia non-HTTPS access issue - -If you opened the HTML file as `file:///` or `http://`, the following error may appear in 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 equivalent error is: - -> Trying to call getUserMedia from an insecure document. - -You get this error because to access the camera with the API [getUserMedia](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia), HTTPS is required. - -*Note* - -- If you use Chrome or Firefox, you might not get the error because these two browsers allow camera access via file:/// and http://localhost. - -To make sure your web application can access the camera, please configure your web server to support HTTPS. The following links may help. - -- NGINX: [Configuring HTTPS servers](https://nginx.org/en/docs/http/configuring_https_servers.html) -- IIS: [Create a Self Signed Certificate in IIS](https://aboutssl.org/how-to-create-a-self-signed-certificate-in-iis/) -- Tomcat: [Setting Up SSL on Tomcat in 5 minutes](https://dzone.com/articles/setting-ssl-tomcat-5-minutes) -- Node.js: [npm tls](https://nodejs.org/docs/v0.4.1/api/tls.html) - -#### Self-signed certificate issue - -For testing purposes, a self-signed certificate can be used when configuring HTTPS. When accessing the site, the browser might say "the site is not secure". In this case, go to the certificate settings and trust this certificate. - -In a production environment, a valid HTTPS certificate is required. - -### Step Three: Time to scan - -Place a barcode in front of the camera. You should see an alert pop up with the decoded barcode result and a coloured region on the video to highlight the barcode location. - -## Installation - -For evaluation purposes, we recommend that you get the official package of the library for developers. The following shows how to acquire the package. - -* From the website - - [Download Dynamsoft Barcode Reader](https://www.dynamsoft.com/barcode-reader/downloads/) - -* yarn - - ``` - $ yarn add dynamsoft-javascript-barcode - ``` - -* npm - - ``` - $ npm install dynamsoft-javascript-barcode --save - ``` - -If you want to start building your application right away, you can also just make use of the library via CDN as shown in the previous helloworld sample code. - -* cdn - - ``` - - - - ``` - -Dynamsoft also provides a Barcode Reader SDK built for Node, see [Dynamsoft JavaScript Barcode SDK for Node](https://github.com/dynamsoft-dbr/node-javascript-barcode). - -## Demos and Examples - -The following are the official demo of the library and examples for the most popular JavaScript Frameworks. - -- [Online demo](https://demo.dynamsoft.com/barcode-reader-js/) -- [Vue example](https://github.com/Dynamsoft/javascript-barcode/tree/master/example/web/vue) -- [React example](https://github.com/Dynamsoft/javascript-barcode/tree/master/example/web/react) -- [Angular example](https://github.com/Dynamsoft/javascript-barcode/tree/master/example/web/angular) - diff --git a/programming-old/javascript/user-guide/index-v8.2.1.md b/programming-old/javascript/user-guide/index-v8.2.1.md deleted file mode 100644 index d645a796..00000000 --- a/programming-old/javascript/user-guide/index-v8.2.1.md +++ /dev/null @@ -1,162 +0,0 @@ ---- -layout: default-layout -title: v8.2.1 User Guide - Dynamsoft Barcode Reader JavaScript Edition -description: This is the user guide of Dynamsoft Barcode Reader JavaScript SDK. -keywords: user guide, javascript, js -breadcrumbText: User Guide -needAutoGenerateSidebar: true -permalink: /programming/javascript/user-guide/index-v8.2.1.html ---- - -# Dynamsoft Barcode Reader JavaScript Edition - User Guide - -![Dynamsoft JavaScript Barcode SDK](assets/dbr-js-sdk.png) - -[Dynamsoft BarcodeReader SDK for Web](https://www.dynamsoft.com/Products/barcode-recognition-javascript.aspx) is a JavaScript SDK for barcode scanning based on **WebAssembly**. It supports real-time barcode localization and decoding of various barcode types. The library is capable of scanning barcodes directly from live video streams as well as static images. It also supports reading multiple barcodes at once. - -In this guide, you will learn step by step how to use Dynamsoft Barcode Reader JavaScript Edition in your application: - -- [Getting Started](#getting-started---hello-world) -- [Installation](#installation) -- [Basic Customizations]({{ site.js }}user-guide/basic-customizations.html) -- [Advanced Customizations]({{ site.js }}user-guide/advanced-customizations.html) -- [Deployment Activation]({{ site.js }}user-guide/deployment-activation.html) -- [Features Requirements]({{ site.js }}user-guide/features-requirements.html) -- [Upgrade]({{ site.js }}user-guide/upgrade.html) - - -## Getting Started - Hello World - -Let's start by using the library to build a simple web application that will decode barcodes from a live video stream. - -### Basic Requirements - -- Internet connection -- [Supported Browser]({{site.js}}user-guide/features-requirements.html#system-requirements) -- Camera access - -### Step One: Write the code in one minute - -Creat a text file anywhere on your local disk and name it "helloworld.html". Copy the following content in the file and save. - -```html - - - - - - - - -``` - -*About the code* - -- `onFrameRead`: This event is triggered after the library finishes scanning a frame from the video stream. The `results` object contains all the barcode results that the library found on this frame. In this example, we print the results to the browser console. - -- `onUnduplicatedRead`: This event is triggered when a new barcode (not a duplicate) is found. `txt` holds the barcode text value while `result` is an object that holds details of the barcode. In this example, an alert will be displayed for each unique barcode found. Notice that if the same barcode is found on multiple consecutive frames, this event is only triggered once. - - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/pL4e7yrd/) - -*Note*: - -- The recommendation is to deploy this page to your web server and run it over **HTTPS**. If you don't have a ready-to-use web server but have a package manager like npm or yarn, you can set up a simple HTTP server in minutes. Check out [http-server on npm](https://www.npmjs.com/package/http-server) or [yarn](https://yarnpkg.com/package/http-server). However, for simple testing purposes, it's perfectly fine to just open the file directly from your local disk. - -- You will need to replace `PRODUCT-KEYS` with a trial key (or your Handshake Code if you have got one) for the sample code to work correctly. You can acquire a trial key [here](https://www.dynamsoft.com/customer/license/trialLicense?utm_source=guide&product=dbr&package=js). Notice that the library will still read barcodes without a valid key (Code), but will return an annotated result string. - -- The library only scans a new frame when it has finished scanning the previous frame. Generally, frames come in faster than the library processes a frame (for 30 FPS, the interval is about 33 ms), therefore not all frames are scanned. - -### Step Two: Enable camera access - -Open the HTML page in your browser and you should see a pop-up asking for permission to access the camera. Once the access is granted, the video stream will start in the default UI of the **BarcodeScanner** object. - -*Note*: - -- If you don't see the pop-up, wait a few seconds for the initialization to finish. - -In this step, you might run into the following issues: - -#### getUserMedia non-HTTPS access issue - -If you opened the HTML file as `file:///` or `http://`, the following error may appear in 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 equivalent error is: - -> Trying to call getUserMedia from an insecure document. - -You get this error because to access the camera with the API [getUserMedia](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia), HTTPS is required. - -*Note* - -- If you use Chrome or Firefox, you might not get the error because these two browsers allow camera access via file:/// and http://localhost. - -To make sure your web application can access the camera, please configure your web server to support HTTPS. The following links may help. - -- NGINX: [Configuring HTTPS servers](https://nginx.org/en/docs/http/configuring_https_servers.html) -- IIS: [Create a Self Signed Certificate in IIS](https://aboutssl.org/how-to-create-a-self-signed-certificate-in-iis/) -- Tomcat: [Setting Up SSL on Tomcat in 5 minutes](https://dzone.com/articles/setting-ssl-tomcat-5-minutes) -- Node.js: [npm tls](https://nodejs.org/docs/v0.4.1/api/tls.html) - -#### Self-signed certificate issue - -For testing purposes, a self-signed certificate can be used when configuring HTTPS. When accessing the site, the browser might say "the site is not secure". In this case, go to the certificate settings and trust this certificate. - -In a production environment, a valid HTTPS certificate is required. - -### Step Three: Time to scan - -Place a barcode in front of the camera. You should see an alert pop up with the decoded barcode result and a coloured region on the video to highlight the barcode location. - -## Installation - -For evaluation purposes, we recommend that you get the official package of the library for developers. The following shows how to acquire the package. - -* From the website - - [Download Dynamsoft Barcode Reader](https://www.dynamsoft.com/barcode-reader/downloads/) - -* yarn - - ``` - $ yarn add dynamsoft-javascript-barcode - ``` - -* npm - - ``` - $ npm install dynamsoft-javascript-barcode --save - ``` - -If you want to start building your application right away, you can also just make use of the library via CDN as shown in the previous helloworld sample code. - -* cdn - - ``` - - - - ``` - -Dynamsoft also provides a Barcode Reader SDK built for Node, see [Dynamsoft JavaScript Barcode SDK for Node](https://github.com/dynamsoft-dbr/node-javascript-barcode). - -## Demos and Examples - -The following are the official demo of the library and examples for the most popular JavaScript Frameworks. - -- [Online demo](https://demo.dynamsoft.com/barcode-reader-js/) -- [Vue example](https://github.com/Dynamsoft/javascript-barcode/tree/master/example/web/vue) -- [React example](https://github.com/Dynamsoft/javascript-barcode/tree/master/example/web/react) -- [Angular example](https://github.com/Dynamsoft/javascript-barcode/tree/master/example/web/angular) - diff --git a/programming-old/javascript/user-guide/index-v8.2.3.md b/programming-old/javascript/user-guide/index-v8.2.3.md deleted file mode 100644 index 7b972af3..00000000 --- a/programming-old/javascript/user-guide/index-v8.2.3.md +++ /dev/null @@ -1,162 +0,0 @@ ---- -layout: default-layout -title: v8.2.3 User Guide - Dynamsoft Barcode Reader JavaScript Edition -description: This is the user guide of Dynamsoft Barcode Reader JavaScript SDK. -keywords: user guide, javascript, js -breadcrumbText: User Guide -needAutoGenerateSidebar: true -permalink: /programming/javascript/user-guide/index-v8.2.3.html ---- - -# Dynamsoft Barcode Reader JavaScript Edition - User Guide - -![Dynamsoft JavaScript Barcode SDK](assets/dbr-js-sdk.png) - -[Dynamsoft BarcodeReader SDK for Web](https://www.dynamsoft.com/Products/barcode-recognition-javascript.aspx) is a JavaScript SDK for barcode scanning based on **WebAssembly**. It supports real-time barcode localization and decoding of various barcode types. The library is capable of scanning barcodes directly from live video streams as well as static images. It also supports reading multiple barcodes at once. - -In this guide, you will learn step by step how to use Dynamsoft Barcode Reader JavaScript Edition in your application: - -- [Getting Started](#getting-started---hello-world) -- [Installation](#installation) -- [Basic Customizations]({{ site.js }}user-guide/basic-customizations.html) -- [Advanced Customizations]({{ site.js }}user-guide/advanced-customizations.html) -- [Deployment Activation]({{ site.js }}user-guide/deployment-activation.html) -- [Features Requirements]({{ site.js }}user-guide/features-requirements.html) -- [Upgrade]({{ site.js }}user-guide/upgrade.html) - - -## Getting Started - Hello World - -Let's start by using the library to build a simple web application that will decode barcodes from a live video stream. - -### Basic Requirements - -- Internet connection -- [Supported Browser]({{site.js}}user-guide/features-requirements.html#system-requirements) -- Camera access - -### Step One: Write the code in one minute - -Creat a text file anywhere on your local disk and name it "helloworld.html". Copy the following content in the file and save. - -```html - - - - - - - - -``` - -*About the code* - -- `onFrameRead`: This event is triggered after the library finishes scanning a frame from the video stream. The `results` object contains all the barcode results that the library found on this frame. In this example, we print the results to the browser console. - -- `onUnduplicatedRead`: This event is triggered when a new barcode (not a duplicate) is found. `txt` holds the barcode text value while `result` is an object that holds details of the barcode. In this example, an alert will be displayed for each unique barcode found. Notice that if the same barcode is found on multiple consecutive frames, this event is only triggered once. - - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/pL4e7yrd/) - -*Note*: - -- The recommendation is to deploy this page to your web server and run it over **HTTPS**. If you don't have a ready-to-use web server but have a package manager like npm or yarn, you can set up a simple HTTP server in minutes. Check out [http-server on npm](https://www.npmjs.com/package/http-server) or [yarn](https://yarnpkg.com/package/http-server). However, for simple testing purposes, it's perfectly fine to just open the file directly from your local disk. - -- You will need to replace `PRODUCT-KEYS` with a trial key (or your Handshake Code if you have got one) for the sample code to work correctly. You can acquire a trial key [here](https://www.dynamsoft.com/customer/license/trialLicense?utm_source=guide&product=dbr&package=js). Notice that the library will still read barcodes without a valid key (Code), but will return an annotated result string. - -- The library only scans a new frame when it has finished scanning the previous frame. Generally, frames come in faster than the library processes a frame (for 30 FPS, the interval is about 33 ms), therefore not all frames are scanned. - -### Step Two: Enable camera access - -Open the HTML page in your browser and you should see a pop-up asking for permission to access the camera. Once the access is granted, the video stream will start in the default UI of the **BarcodeScanner** object. - -*Note*: - -- If you don't see the pop-up, wait a few seconds for the initialization to finish. - -In this step, you might run into the following issues: - -#### getUserMedia non-HTTPS access issue - -If you opened the HTML file as `file:///` or `http://`, the following error may appear in 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 equivalent error is: - -> Trying to call getUserMedia from an insecure document. - -You get this error because to access the camera with the API [getUserMedia](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia), HTTPS is required. - -*Note* - -- If you use Chrome or Firefox, you might not get the error because these two browsers allow camera access via file:/// and http://localhost. - -To make sure your web application can access the camera, please configure your web server to support HTTPS. The following links may help. - -- NGINX: [Configuring HTTPS servers](https://nginx.org/en/docs/http/configuring_https_servers.html) -- IIS: [Create a Self Signed Certificate in IIS](https://aboutssl.org/how-to-create-a-self-signed-certificate-in-iis/) -- Tomcat: [Setting Up SSL on Tomcat in 5 minutes](https://dzone.com/articles/setting-ssl-tomcat-5-minutes) -- Node.js: [npm tls](https://nodejs.org/docs/v0.4.1/api/tls.html) - -#### Self-signed certificate issue - -For testing purposes, a self-signed certificate can be used when configuring HTTPS. When accessing the site, the browser might say "the site is not secure". In this case, go to the certificate settings and trust this certificate. - -In a production environment, a valid HTTPS certificate is required. - -### Step Three: Time to scan - -Place a barcode in front of the camera. You should see an alert pop up with the decoded barcode result and a coloured region on the video to highlight the barcode location. - -## Installation - -For evaluation purposes, we recommend that you get the official package of the library for developers. The following shows how to acquire the package. - -* From the website - - [Download Dynamsoft Barcode Reader](https://www.dynamsoft.com/barcode-reader/downloads/) - -* yarn - - ``` - $ yarn add dynamsoft-javascript-barcode - ``` - -* npm - - ``` - $ npm install dynamsoft-javascript-barcode --save - ``` - -If you want to start building your application right away, you can also just make use of the library via CDN as shown in the previous helloworld sample code. - -* cdn - - ``` - - - - ``` - -Dynamsoft also provides a Barcode Reader SDK built for Node, see [Dynamsoft JavaScript Barcode SDK for Node](https://github.com/dynamsoft-dbr/node-javascript-barcode). - -## Demos and Examples - -The following are the official demo of the library and examples for the most popular JavaScript Frameworks. - -- [Online demo](https://demo.dynamsoft.com/barcode-reader-js/) -- [Vue example](https://github.com/Dynamsoft/javascript-barcode/tree/master/example/web/vue) -- [React example](https://github.com/Dynamsoft/javascript-barcode/tree/master/example/web/react) -- [Angular example](https://github.com/Dynamsoft/javascript-barcode/tree/master/example/web/angular) - diff --git a/programming-old/javascript/user-guide/index-v8.2.5.md b/programming-old/javascript/user-guide/index-v8.2.5.md deleted file mode 100644 index df4bfb5f..00000000 --- a/programming-old/javascript/user-guide/index-v8.2.5.md +++ /dev/null @@ -1,548 +0,0 @@ ---- -layout: default-layout -title: v8.2.5 User Guide - Dynamsoft Barcode Reader JavaScript Edition -description: This is the user guide of Dynamsoft Barcode Reader JavaScript SDK. -keywords: user guide, javascript, js -breadcrumbText: User Guide -noTitleIndex: true -needGenerateH3Content: true -needAutoGenerateSidebar: true -permalink: /programming/javascript/user-guide/index-v8.2.5.html ---- - -# Dynamsoft Barcode Reader for Your Website - -Turn your web page into a barcode scanner with just a few lines of code. - -![version](https://img.shields.io/npm/v/dynamsoft-javascript-barcode.svg) -![downloads](https://img.shields.io/npm/dm/dynamsoft-javascript-barcode.svg) -![jsdelivr](https://img.shields.io/jsdelivr/npm/hm/dynamsoft-javascript-barcode.svg) -![](https://img.shields.io/snyk/vulnerabilities/npm/dynamsoft-javascript-barcode.svg) - -[![](https://img.shields.io/badge/Download-Offline%20SDK-orange)](https://www.dynamsoft.com/barcode-reader/downloads/?utm_source=github&product=dbr&package=js) - -Once integrated, your users can open your website in a browser, access their cameras and read barcodes directly from the video input. - -In this guide, you will learn step by step on how to integrate this library into your website. - -> For back-end barcode reading with Node.js, also see [Dynamsoft Barcode Reader for Node](https://github.com/Dynamsoft/javascript-barcode/blob/master/README.NODE.md). - -Table of Contents: - -* [Hello World - Simplest Implementation](#hello-world---simplest-implementation) -* [Building your own page](#building-your-own-page) - - [Include the library](#include-the-library) - - [Configure the library](#configure-the-library) - - [Interact with the library](#interact-with-the-library) -* [Requesting A Trial](#requesting-a-trial) -* [System Requirements](#system-requirements) -* [Hosting the Library](#hosting-the-library) -* [Advanced Usage](#advanced-usage) -* [How to Upgrade](#how-to-upgrade) -* [FAQ](#faq) - -Example Code: - -* [Use the library in Angular](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/master/1.hello-world/3.read-video-angular) -* [Use the library in React](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/master/1.hello-world/4.read-video-react) -* [Use the library in Vue](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/master/1.hello-world/5.read-video-vue) - -You can also: - -* [Try All Online Examples](https://demo.dynamsoft.com/Samples/DBR/JS/index.html) -* [Try the Official Demo](https://demo.dynamsoft.com/barcode-reader-js/) - -## Hello World - Simplest Implementation - -Let's start by testing the "Hello World" example of the library which demonstrates how to use the minimum code to enable a web page to read barcodes from a live video stream. - -* Basic Requirements - + Internet connection - + [A supported browser](#system-requirements) - + Camera access - -### Step One: Check the code of the example - -The complete code of the "Hello World" example is shown below - -``` html - - - - - - - - - -``` - -> You can also find the code (with more comments) [on GitHub](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/master/1.hello-world/1.minimum-code.html). - -*About the code* - - + `createInstance()`: This method creates a `BarcodeScanner` object. This object can read barcodes directly from a video input with the help of its interactive UI (hidden by default) and the [MediaDevices interface](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices). - - + `onFrameRead`: This event is triggered every time the library finishes scanning a video frame. The `results` object contains all the barcode results that the library have found on this frame. In this example, we print the results to the browser console. - - + `onUnduplicatedRead`: This event is triggered when the library finds a new barcode, which is not a duplicate among multiple frames. `txt` holds the barcode text value while `result` is an object that holds details of the barcode. In this example, an alert will be displayed for this new barcode. - - + `show()`: This method brings up the built-in UI of the `BarcodeScanner` object. - -### Step Two: Test the example - -You can choose one of three ways to test the example: - -* [Hello World example](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/1.minimum-code.html) -* [Hello World example via JSFiddle](https://jsfiddle.net/DynamsoftTeam/pL4e7yrd/) -* [Download a copy](https://tst.dynamsoft.com/public/download/dbr/browser/code/helloworld.zip) of the example code and set it up locally - -Either way, you open the example page in a browser, allow the page to access your camera and the video will show up on the page. After that, you can point the camera at something with a barcode to read it. - -If the barcode is decoded, an alert will pop up with the result text. At the same time, the barcode location will be highlighted in the video feed. - - > For first use, you may need to wait a few seconds for the library to initialize. - -*Note*: - - + The library only scans a new frame when it has finished scanning the previous frame. The interval between two consecutive frames might not be enough time for the library to process the 1st frame (for 30 FPS, the interval is about 33 ms), therefore, not all frames are scanned. - - + The library requires a license to work. However, when no license is specified in the code, a [free public trial license](https://www.dynamsoft.com/license-server/docs/about/terms.html?ver=latest#public-trial-license?utm_source=guide) will automatically be used during which you can make initial evaluation of the library to decide whether or not you want to evaluate it further. If you do, you can [request a trial](#requesting-a-trial). - - > Network connection is required for the free public trial license to work. - -If the test doesn't go as expected, you can check out the [FAQ](#faq) or [contact us](https://www.dynamsoft.com/contact/). - -## Building your own page - -### Include the library - -#### Use a CDN - -The simplest way to include the library is to use either the [jsDelivr](https://jsdelivr.com/) or [UNPKG](https://unpkg.com/) CDN. The "hello world" example above uses **jsDelivr**. - -* jsDelivr - - ``` html - - ``` - -* UNPKG - - ``` html - - ``` - -#### Host the library yourself (recommended) - -Besides using the CDN, you can also download the library and host its files on your own website / server before including it in your application. - -The following shows a few ways to download the library. - -* From the website - - [Download the JavaScript Package](https://www.dynamsoft.com/barcode-reader/downloads/) - -* yarn - - ```cmd - $ yarn add dynamsoft-javascript-barcode - ``` - -* npm - - ``` - $ npm install dynamsoft-javascript-barcode --save - ``` - -Depending on how you downloaded the library and where you put it. You can typically include it like this: - -``` html - -``` - -or - -``` html - -``` - -Read more on [how to host the library](#hosting-the-library). - -### Configure the library - -Before using the library, you need to configure a few things. - -#### Specify the license - - The library requires a license to work, use the APIs `organizationID` and `handshakeCode` to specify how to acquire the license. - - ``` javascript - Dynamsoft.DBR.BarcodeScanner.organizationID = "YOUR-ORGANIZATION-ID"; // Required. - Dynamsoft.DBR.BarcodeScanner.handshakeCode = "A-SPECIFIC-HANDSHAKECODE"; // Optional, if not specified, the default handshake code is used. - Dynamsoft.DBR.BarcodeScanner.sessionPassword = "PASSWORD-TO-PROTECT-YOUR-LICENSE"; // Optional but recomended, use it to protect your license. - Dynamsoft.DBR.BarcodeScanner.licenseServer = ["YOUR-OWN-MAIN-LTS", "YOUR-OWN-STANDBY-LTS"]; //Optional, ignore this line if you are using Dynamsoft-hosting LTS. - ``` - - *Note*: - - + Network connection is required for the license to work. - + If nothing is specified like the above "hello world" example, a [free public trial license](https://www.dynamsoft.com/license-server/docs/about/terms.html?ver=latest#public-trial-license?utm_source=guide) will be automatically used. - + The license is actually fetched during the creation of an `BarcodeScanner` or `BarcodeReader` object. - + If a public network connection is not available, you can choose to host a license server in your private network. - - An alternative way to specify the license is to use an alphanumeric string which does not require a network connection. The following shows how it could be used. [Contact us](https://www.dynamsoft.com/contact/) for more information. - - ```javascript - Dynamsoft.DBR.BarcodeReader.productKeys = "t0068NQAAACgTVU2aucyxqETXKkiomqhV7YoLrnqjLiQQRSH5DBV1UtIs4..." - ``` - - Or - - ```html - - ``` - - -#### Specify the location of the "engine" files - - The "engine" files refer to *.worker.js, *.wasm.js and *.wasm, etc. which are loaded by the main library at runtime. This configuration option uses the API `engineResourcePath` and is often not required as these files usually are in the same location with the main library file (dbr.js). However, in cases where the engine files are not in the same location as the main library file (for example, with frameworks like Angular or React, dbr.js is compiled into another file), this configuration will be required. - - The following code uses the jsDelivr CDN, feel free to change it to your own location of these files. - - ``` javascript - import DBR from "dynamsoft-javascript-barcode"; - DBR.BarcodeScanner.engineResourcePath = "https://cdn.jsdelivr.net/npm/dynamsoft-javascript-barcode@8.2.5/dist/"; - export default DBR; - ``` - -#### Specify which engine to use - - The library comes with two engines: "compact" and "full". They may be merged into one in the future, but right now you can choose one to use. - - By default, the compact engine is used. The following line changes it to the full engine. - - ``` javascript - Dynamsoft.DBR.BarcodeScanner._bUseFullFeature = true; - ``` - - The following table compares the features between the two engines: - - | Features | Compact edition | Full edition | - |:-:|:-:|:-:| - | *.wasm* size*\(gzip\) | 897 KB | 1.2 MB | - | 1D | ✓ | ✓ | - | QR | ✓ | ✓ | - | Micro QR | - | ✓ | - | PDF417 | ✓ | ✓ | - | Micro PDF417 | - | ✓ | - | DataMatrix | ✓ | ✓ | - | Aztec | - | ✓ | - | MaxiCode | - | ✓ | - | Patch Code | - | ✓ | - | GS1 Composite Code | - | ✓ | - | GS1 DataBar | - | ✓ | - | DotCode | - | ✓ | - | Postal Code | - | ✓ | - | DPM | - | ✓ | - | getRuntimeSettings | ✓ | ✓ | - | updateRuntimeSettings | ✓ | ✓ | - | getIntermediateResults | - | ✓ | - | initRuntimeSettingsWithString | - | ✓ | - | outputSettingsToString | - | ✓ | - - * The file size is version 8.2.5. In other versions, the size may be different. - -### Interact with the library - -#### Create a `BarcodeScanner` object - -You can use one of two classes ( `BarcodeScanner` and `BarcodeReader` ) to interact with the library. `BarcodeReader` is a low-level class that processes images directly. `BarcodeScanner` , on the other hand, inherits from `BarcodeReader` and provides high-level APIs and a built-in UI to allow barcode scanning via cameras. We'll focus on `BarcodeScanner` in this guide. - -To use the library, we first create a `BarcodeScanner` object. - -``` javascript -try { - await Dynamsoft.DBR.BarcodeScanner.createInstance(); -} catch (ex) { - console.error(ex); -} -``` - -*Note*: - -* The creation of an object consists of two parallel tasks: one is to download and compile the "engine", the other is to fetch a license from the License Tracking Server (assuming an online license is used). - -#### Configure the `BarcodeScanner` object - -Let's take a look at the following code snippets first: - -``` javascript -// set which camera and what resolution to use -await scanner.updateVideoSettings({ - video: { - width: 1280, - height: 720, - facingMode: "environment" - } -}); -``` - -``` javascript -// set up the scanner behavior -let scanSettings = await scanner.getScanSettings(); -// disregard duplicated results found in a specified time period -scanSettings.duplicateForgetTime = 20000; -// set a scan interval so the library may release the CPU from time to time -scanSettings.intervalTime = 300; -await scanner.updateScanSettings(scanSettings); -``` - -``` javascript -// use one of the built-in RuntimeSetting templates: "single" (decode a single barcode, default mode), "speed", "balance", "coverage". "speed" is recommended for decoding from a video stream -await scanner.updateRuntimeSettings("speed"); - -// make changes to the template. The code below demonstrates how to specify which symbologies are enabled -let runtimeSettings = await scanner.getRuntimeSettings(); -runtimeSettings.barcodeFormatIds = Dynamsoft.DBR.EnumBarcodeFormat.BF_ONED | Dynamsoft.DBR.EnumBarcodeFormat.BF_QR_CODE; -await scanner.updateRuntimeSettings(runtimeSettings); -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/yfkcajxz/) - -As you can see from the above code snippets, there are three types of configurations: - -* `get/updateVideoSettings`: Configures the data source, i.e., the camera. These settings include which camera to use, the resolution, etc. Learn more [here](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia#Syntax). - -* `get/updateScanSettings`: Configures the behavior of the scanner which includes `duplicateForgetTime`, `intervalTime` and `filter`, etc. - -* `get/updateRuntimeSettings`: Configures the decode engine. Find a full list of these settings and their corresponding descriptions [here](https://www.dynamsoft.com/barcode-reader/programming/javascript/api-reference/global-interfaces.html#runtimesettings). For example, the following uses the built-in "speed" settings with updated `localizationModes`. - - ``` javascript - await barcodeScanner.updateRuntimeSettings("speed"); - //await barcodeScanner.updateRuntimeSettings("balance"); //alternative - //await barcodeScanner.updateRuntimeSettings("coverage"); //alternative - let settings = await barcodeScanner.getRuntimeSettings(); - settings.localizationModes = [ - Dynamsoft.DBR.EnumLocalizationMode.LM_CONNECTED_BLOCKS, - Dynamsoft.DBR.EnumLocalizationMode.LM_SCAN_DIRECTLY, - Dynamsoft.DBR.EnumLocalizationMode.LM_LINES, 0, 0, 0, 0, 0 - ]; - await barcodeScanner.updateRuntimeSettings(settings); - ``` - - Try in [JSFiddle](https://jsfiddle.net/DynamsoftTeam/f24h8c1m/). - -#### Customize the UI - -The built-in UI of the `BarcodeScanner` object is defined in the file `dist/dbr.scanner.html` . There are a few ways to customize it: - -* Modify the file `dist/dbr.scanner.html` directly. - - This option is only possible when you host this file on your own web server instead of using a CDN. - -* Copy the file `dist/dbr.scanner.html` to your application, modify it and use the the API `defaultUIElementURL` to set it as the default UI. - - ``` javascript - Dynamsoft.DBR.BarcodeScanner.defaultUIElementURL = "THE-URL-TO-THE-FILE"; - ``` - - > You must set `defaultUIElementURL` before you call `createInstance()` . - -* Append the default UI element to your page, customize it before showing it. - - ``` html -
- ``` - - ``` javascript - document.getElementById('scannerUI').appendChild(scanner.getUIElement()); - document.getElementsByClassName('dbrScanner-btn-close')[0].hidden = true; // Hide the close button - ``` - -* Build the UI element into your own web page and specify it with the API `setUIElement(HTMLElement)`. - - - Embed the video - - ``` html -
- -
- - ``` - - > The video element must have the class `dbrScanner-video` . - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/2jzeq1r6/) - - - Add the camera list and resolution list - - If the class names for these lists match the default ones, `dbrScanner-sel-camera` and `dbrScanner-sel-resolution` , the library will automatically populate the lists and handle the camera/resolution switching. - - ``` html - - ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/nbj75vxu/) - - ``` html - - ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/25v08paf/) - - > By default, 8 hard-coded resolutions are populated as options. You can show only a custom set of options by hardcoding them. - - ``` html - - ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/tnfjks4q/) - - > Generally, you need to provide a resolution that the camera supports. However, in case a camera does not support the specified resolution, it usually uses the nearest supported resolution. As a result, the selected resolution may not be the actual resolution used. In this case, add an option with the class name `dbrScanner-opt-gotResolution` (as shown above) and the library will then use it to show the actual resolution. - -Interested to test it further? Read on to learn how to request a 30-day free trial. - -## Requesting A Trial - -Since v8.2.5, a free public trial license is used by default if no license is specified. - -> Network connection is required for the free public trial license to work. - -After that, if you want to evaluate the library further, you can [register for a Dynamsoft account](https://www.dynamsoft.com/api-common/Regist/Regist) (if you haven't already done so) and request a 30-day trial license via the Request a Trial License link. - -* If you like, you can also [contact our support team](https://www.dynamsoft.com/contact/) to get a trial extension. - -## System Requirements - -This library requires the following features which are supported by all modern mainstream browsers: - -* `WebAssembly`, `Blob`, `URL`/`createObjectURL`, `Web Workers` - - These four features are required for the library to work. - -* `MediaDevices`/`getUserMedia` - - This API is only required for in-browser video streaming. If a browser does not support this API, the [Single Frame Mode](https://www.dynamsoft.com/barcode-reader/programming/javascript/api-reference/BarcodeScanner/properties.html?ver=latest#singleframemode) will be used automatically. If the API exists but doesn't work correctly, the Single Frame Mode can be used as an alternative way to access the camera. - -The following table is a list of supported browsers based on the above requirements: - -Browser Name | Version -:-: | :-: -Chrome | v57+ (v59+ on Android/iOS1) -Firefox | v52+ (v55+ on Android/iOS1) -Edge2 | v16+ -Safari3 | v11+ - -1 iOS 14.3+ is required for camera video streaming in Chrome and Firefox or Apps using webviews. - -2 On Edge, due to strict Same-origin policy, you must host the library files on the same domain as your web page. - -3 Safari 11.2.2 ~ 11.2.6 are not supported. - -Apart from the browsers, the operating systems may impose some limitations of their own that could restrict the use of the library. Browser compatibility ultimately depends on whether the browser on that particular operating system supports the features listed above. - -## Hosting the library - -### Step One: Deploy the dist folder - -Once you have downloaded the library, you can locate the "dist" directory and copy it to your server (usually as part of your website / web application). The following shows some of the files in this directory: - -* `dbr.js` // The main library file -* `dbr.browser.mjs` // For using the library as a module (` -``` - -Optionally, you may also need to (specify the location of the "engine" files)[#specify-the-location-of-the-engine-files]. - - -## Advanced Usage - -In addition to the content mentioned above, the library has many other settings and options that you can adjust to best suit your usage. To read more, please see [advanced usage](https://www.dynamsoft.com/barcode-reader/programming/javascript/user-guide/advanced-usage.html?ver=latest). - -## How to Upgrade - -If you are using an older version of the library and want to upgrade it to the latest version, please read more on [how to upgrade](https://www.dynamsoft.com/barcode-reader/programming/javascript/user-guide/upgrade.html?ver=latest). - -## FAQ - -### Can I open the web page directly from the hard drive? - -Yes, for simple testing purposes, it's perfectly fine to open the file directly from the hard drive. However, you might encounter some issues in doing so (like unable to access the camera, etc.). The recommendation is to deploy this page to your web server and run it over **HTTPS**. If you don't have a ready-to-use web server but have a package manager like *npm* or *yarn*, you can set up a simple HTTP server in minutes. Check out [http-server on npm](https://www.npmjs.com/package/http-server) or [yarn](https://yarnpkg.com/package/http-server). - -### Why can't I use my camera? - -If you open the web page as `file:///` or `http://`, the camera may not work and you see the following error in 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 equivalent error is: - -> Trying to call getUserMedia from an insecure document. - -You get this error because the API [getUserMedia](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia) requires HTTPS to access the camera. - -* If you use Chrome or Firefox, you might not get the error because these two browsers allow camera access via file:/// and http://localhost. - -To make sure your web application can access the camera, please configure your web server to support HTTPS. The following links may help. - - - NGINX: [Configuring HTTPS servers](https://nginx.org/en/docs/http/configuring_https_servers.html) - - IIS: [Create a Self Signed Certificate in IIS](https://aboutssl.org/how-to-create-a-self-signed-certificate-in-iis/) - - Tomcat: [Setting Up SSL on Tomcat in 5 minutes](https://dzone.com/articles/setting-ssl-tomcat-5-minutes) - - Node.js: [npm tls](https://nodejs.org/docs/v0.4.1/api/tls.html) diff --git a/programming-old/javascript/user-guide/index-v8.4.0.md b/programming-old/javascript/user-guide/index-v8.4.0.md deleted file mode 100644 index 8e0033a2..00000000 --- a/programming-old/javascript/user-guide/index-v8.4.0.md +++ /dev/null @@ -1,549 +0,0 @@ ---- -layout: default-layout -title: v8.4.0 User Guide - Dynamsoft Barcode Reader JavaScript Edition -description: This is the user guide of Dynamsoft Barcode Reader JavaScript SDK. -keywords: user guide, javascript, js -breadcrumbText: User Guide -noTitleIndex: true -needGenerateH3Content: true -needAutoGenerateSidebar: true -permalink: /programming/javascript/user-guide/index-v8.4.0.html ---- - -# Dynamsoft Barcode Reader for Your Website - -Turn your web page into a barcode scanner with just a few lines of code. - -![version](https://img.shields.io/npm/v/dynamsoft-javascript-barcode.svg) -![downloads](https://img.shields.io/npm/dm/dynamsoft-javascript-barcode.svg) -![jsdelivr](https://img.shields.io/jsdelivr/npm/hm/dynamsoft-javascript-barcode.svg) -![](https://img.shields.io/snyk/vulnerabilities/npm/dynamsoft-javascript-barcode.svg) - -[![](https://img.shields.io/badge/Download-Offline%20SDK-orange)](https://www.dynamsoft.com/barcode-reader/downloads/?utm_source=github&product=dbr&package=js) - -Once integrated, your users can open your website in a browser, access their cameras and read barcodes directly from the video input. - -In this guide, you will learn step by step on how to integrate this library into your website. - -> For back-end barcode reading with Node.js, also see [Dynamsoft Barcode Reader for Node](https://github.com/Dynamsoft/javascript-barcode/blob/master/README.NODE.md). - -**Table of Contents** - -* [Hello World - Simplest Implementation](#hello-world---simplest-implementation) -* [Building your own page](#building-your-own-page) - - [Include the library](#include-the-library) - - [Configure the library](#configure-the-library) - - [Interact with the library](#interact-with-the-library) -* [Requesting A Trial](#requesting-a-trial) -* [System Requirements](#system-requirements) -* [Hosting the Library](#hosting-the-library) -* [Advanced Usage](#advanced-usage) -* [How to Upgrade](#how-to-upgrade) -* [FAQ](#faq) - -**Example Code** - -* [Use the library in Angular](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/master/1.hello-world/3.read-video-angular) -* [Use the library in React](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/master/1.hello-world/4.read-video-react) -* [Use the library in Vue](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/master/1.hello-world/5.read-video-vue) - -You can also: - -* [Try All Online Examples](https://demo.dynamsoft.com/Samples/DBR/JS/index.html) -* [Try the Official Demo](https://demo.dynamsoft.com/barcode-reader-js/) - -## Hello World - Simplest Implementation - -Let's start by testing the "Hello World" example of the library which demonstrates how to use the minimum code to enable a web page to read barcodes from a live video stream. - -* Basic Requirements - + Internet connection - + [A supported browser](#system-requirements) - + Camera access - -### Step One: Check the code of the example - -The complete code of the "Hello World" example is shown below - -``` html - - - - - - - - - -``` - -> You can also find the code (with more comments) [on GitHub](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/master/1.hello-world/1.minimum-code.html). - -*About the code* - - + `createInstance()`: This method creates a `BarcodeScanner` object. This object can read barcodes directly from a video input with the help of its interactive UI (hidden by default) and the [MediaDevices interface](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices). - - + `onFrameRead`: This event is triggered every time the library finishes scanning a video frame. The `results` object contains all the barcode results that the library have found on this frame. In this example, we print the results to the browser console. - - + `onUnduplicatedRead`: This event is triggered when the library finds a new barcode, which is not a duplicate among multiple frames. `txt` holds the barcode text value while `result` is an object that holds details of the barcode. In this example, an alert will be displayed for this new barcode. - - + `show()`: This method brings up the built-in UI of the `BarcodeScanner` object. - -### Step Two: Test the example - -You can choose one of three ways to test the example: - -* [Hello World example](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/1.minimum-code.html) -* [Hello World example via JSFiddle](https://jsfiddle.net/DynamsoftTeam/pL4e7yrd/) -* [Download a copy](https://tst.dynamsoft.com/public/download/dbr/browser/code/helloworld.zip) of the example code and set it up locally - -Either way, you open the example page in a browser, allow the page to access your camera and the video will show up on the page. After that, you can point the camera at something with a barcode to read it. - -If the barcode is decoded, an alert will pop up with the result text. At the same time, the barcode location will be highlighted in the video feed. - - > For first use, you may need to wait a few seconds for the library to initialize. - -*Note*: - - + The library only scans a new frame when it has finished scanning the previous frame. The interval between two consecutive frames might not be enough time for the library to process the 1st frame (for 30 FPS, the interval is about 33 ms), therefore, not all frames are scanned. - - + The library requires a license to work. However, when no license is specified in the code, a [free public trial license](https://www.dynamsoft.com/license-server/docs/about/terms.html?ver=latest#public-trial-license?utm_source=guide) will automatically be used during which you can make initial evaluation of the library to decide whether or not you want to evaluate it further. If you do, you can [request a trial](#requesting-a-trial). - - > Network connection is required for the free public trial license to work. - -If the test doesn't go as expected, you can check out the [FAQ](#faq) or [contact us](https://www.dynamsoft.com/contact/). - -## Building your own page - -### Include the library - -#### Use a CDN - -The simplest way to include the library is to use either the [jsDelivr](https://jsdelivr.com/) or [UNPKG](https://unpkg.com/) CDN. The "hello world" example above uses **jsDelivr**. - -* jsDelivr - - ``` html - - ``` - -* UNPKG - - ``` html - - ``` - -#### Host the library yourself (recommended) - -Besides using the CDN, you can also download the library and host its files on your own website / server before including it in your application. - -The following shows a few ways to download the library. - -* From the website - - [Download the JavaScript Package](https://www.dynamsoft.com/barcode-reader/downloads/) - -* yarn - - ```cmd - $ yarn add dynamsoft-javascript-barcode - ``` - -* npm - - ``` - $ npm install dynamsoft-javascript-barcode --save - ``` - -Depending on how you downloaded the library and where you put it. You can typically include it like this: - -``` html - -``` - -or - -``` html - -``` - -Read more on [how to host the library](#hosting-the-library). - -### Configure the library - -Before using the library, you need to configure a few things. - -#### Specify the license - - The library requires a license to work, use the APIs `organizationID` and `handshakeCode` to specify how to acquire the license. - - ``` javascript - Dynamsoft.DBR.BarcodeScanner.organizationID = "YOUR-ORGANIZATION-ID"; // Required. - Dynamsoft.DBR.BarcodeScanner.handshakeCode = "A-SPECIFIC-HANDSHAKECODE"; // Optional, if not specified, the default handshake code is used. - Dynamsoft.DBR.BarcodeScanner.sessionPassword = "PASSWORD-TO-PROTECT-YOUR-LICENSE"; // Optional but recomended, use it to protect your license. - Dynamsoft.DBR.BarcodeScanner.licenseServer = ["YOUR-OWN-MAIN-LTS", "YOUR-OWN-STANDBY-LTS"]; //Optional, ignore this line if you are using Dynamsoft-hosting LTS. - ``` - - *Note*: - - + Network connection is required for the license to work. - + If nothing is specified like the above "hello world" example, a [free public trial license](https://www.dynamsoft.com/license-server/docs/about/terms.html?ver=latest#public-trial-license?utm_source=guide) will be automatically used. - + The license is actually fetched during the creation of an `BarcodeScanner` or `BarcodeReader` object. - + If a public network connection is not available, you can choose to host a license server in your private network. - - An alternative way to specify the license is to use an alphanumeric string which does not require a network connection. The following shows how it could be used. [Contact us](https://www.dynamsoft.com/contact/) for more information. - - ```javascript - Dynamsoft.DBR.BarcodeReader.productKeys = "t0068NQAAACgTVU2aucyxqETXKkiomqhV7YoLrnqjLiQQRSH5DBV1UtIs4..." - ``` - - Or - - ```html - - ``` - - -#### Specify the location of the "engine" files - - The "engine" files refer to *.worker.js, *.wasm.js and *.wasm, etc. which are loaded by the main library at runtime. This configuration option uses the API `engineResourcePath` and is often not required as these files usually are in the same location with the main library file (dbr.js). However, in cases where the engine files are not in the same location as the main library file (for example, with frameworks like Angular or React, dbr.js is compiled into another file), this configuration will be required. - - The following code uses the jsDelivr CDN, feel free to change it to your own location of these files. - - ``` javascript - import DBR from "dynamsoft-javascript-barcode"; - DBR.BarcodeScanner.engineResourcePath = "https://cdn.jsdelivr.net/npm/dynamsoft-javascript-barcode@8.4.0/dist/"; - export default DBR; - ``` - -#### Specify which engine to use - - The library comes with two engines: "compact" and "full". They may be merged into one in the future, but right now you can choose one to use. - - By default, the compact engine is used. The following line changes it to the full engine. - - ``` javascript - Dynamsoft.DBR.BarcodeScanner._bUseFullFeature = true; - ``` - - The following table compares the features between the two engines: - - | Features | Compact edition | Full edition | - |:-:|:-:|:-:| - | *.wasm* size*\(gzip\) | 910 KB | 1.2 MB | - | 1D | ✓ | ✓ | - | QR | ✓ | ✓ | - | Micro QR | - | ✓ | - | PDF417 | ✓ | ✓ | - | Micro PDF417 | - | ✓ | - | DataMatrix | ✓ | ✓ | - | Aztec | - | ✓ | - | MaxiCode | - | ✓ | - | Patch Code | - | ✓ | - | GS1 Composite Code | - | ✓ | - | GS1 DataBar | - | ✓ | - | DotCode | - | ✓ | - | Postal Code | - | ✓ | - | DPM | - | ✓ | - | getRuntimeSettings | ✓ | ✓ | - | updateRuntimeSettings | ✓ | ✓ | - | getIntermediateResults | - | ✓ | - | initRuntimeSettingsWithString | - | ✓ | - | outputSettingsToString | - | ✓ | - - * The file size is version 8.4.0. In other versions, the size may be different. - -### Interact with the library - -#### Create a `BarcodeScanner` object - -You can use one of two classes ( `BarcodeScanner` and `BarcodeReader` ) to interact with the library. `BarcodeReader` is a low-level class that processes images directly. `BarcodeScanner` , on the other hand, inherits from `BarcodeReader` and provides high-level APIs and a built-in UI to allow barcode scanning via cameras. We'll focus on `BarcodeScanner` in this guide. - -To use the library, we first create a `BarcodeScanner` object. - -``` javascript -try { - await Dynamsoft.DBR.BarcodeScanner.createInstance(); -} catch (ex) { - console.error(ex); -} -``` - -*Note*: - -* The creation of an object consists of two parallel tasks: one is to download and compile the "engine", the other is to fetch a license from the License Tracking Server (assuming an online license is used). - -#### Configure the `BarcodeScanner` object - -Let's take a look at the following code snippets first: - -``` javascript -// set which camera and what resolution to use -await scanner.updateVideoSettings({ - video: { - width: 1280, - height: 720, - facingMode: "environment" - } -}); -``` - -``` javascript -// set up the scanner behavior -let scanSettings = await scanner.getScanSettings(); -// disregard duplicated results found in a specified time period -scanSettings.duplicateForgetTime = 20000; -// set a scan interval so the library may release the CPU from time to time -scanSettings.intervalTime = 300; -await scanner.updateScanSettings(scanSettings); -``` - -``` javascript -// use one of the built-in RuntimeSetting templates: "single" (decode a single barcode, default mode), "speed", "balance", "coverage". "speed" is recommended for decoding from a video stream -await scanner.updateRuntimeSettings("speed"); - -// make changes to the template. The code below demonstrates how to specify which symbologies are enabled -let runtimeSettings = await scanner.getRuntimeSettings(); -runtimeSettings.barcodeFormatIds = Dynamsoft.DBR.EnumBarcodeFormat.BF_ONED | Dynamsoft.DBR.EnumBarcodeFormat.BF_QR_CODE; -await scanner.updateRuntimeSettings(runtimeSettings); -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/yfkcajxz/) - -As you can see from the above code snippets, there are three types of configurations: - -* `get/updateVideoSettings`: Configures the data source, i.e., the camera. These settings include which camera to use, the resolution, etc. Learn more [here](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia#Syntax). - -* `get/updateScanSettings`: Configures the behavior of the scanner which includes `duplicateForgetTime`, `intervalTime` and `filter`, etc. - -* `get/updateRuntimeSettings`: Configures the decode engine. Find a full list of these settings and their corresponding descriptions [here](https://www.dynamsoft.com/barcode-reader/programming/javascript/api-reference/global-interfaces.html#runtimesettings). For example, the following uses the built-in "speed" settings with updated `localizationModes`. - - ``` javascript - await barcodeScanner.updateRuntimeSettings("speed"); - //await barcodeScanner.updateRuntimeSettings("balance"); //alternative - //await barcodeScanner.updateRuntimeSettings("coverage"); //alternative - let settings = await barcodeScanner.getRuntimeSettings(); - settings.localizationModes = [ - Dynamsoft.DBR.EnumLocalizationMode.LM_CONNECTED_BLOCKS, - Dynamsoft.DBR.EnumLocalizationMode.LM_SCAN_DIRECTLY, - Dynamsoft.DBR.EnumLocalizationMode.LM_LINES, 0, 0, 0, 0, 0 - ]; - await barcodeScanner.updateRuntimeSettings(settings); - ``` - - Try in [JSFiddle](https://jsfiddle.net/DynamsoftTeam/f24h8c1m/). - -#### Customize the UI - -The built-in UI of the `BarcodeScanner` object is defined in the file `dist/dbr.scanner.html` . There are a few ways to customize it: - -* Modify the file `dist/dbr.scanner.html` directly. - - This option is only possible when you host this file on your own web server instead of using a CDN. - -* Copy the file `dist/dbr.scanner.html` to your application, modify it and use the the API `defaultUIElementURL` to set it as the default UI. - - ``` javascript - Dynamsoft.DBR.BarcodeScanner.defaultUIElementURL = "THE-URL-TO-THE-FILE"; - ``` - - > You must set `defaultUIElementURL` before you call `createInstance()` . - -* Append the default UI element to your page, customize it before showing it. - - ``` html -
- ``` - - ``` javascript - document.getElementById('scannerUI').appendChild(scanner.getUIElement()); - document.getElementsByClassName('dbrScanner-btn-close')[0].hidden = true; // Hide the close button - ``` - -* Build the UI element into your own web page and specify it with the API `setUIElement(HTMLElement)`. - - - Embed the video - - ``` html -
- -
- - ``` - - > The video element must have the class `dbrScanner-video` . - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/2jzeq1r6/) - - - Add the camera list and resolution list - - If the class names for these lists match the default ones, `dbrScanner-sel-camera` and `dbrScanner-sel-resolution` , the library will automatically populate the lists and handle the camera/resolution switching. - - ``` html - - ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/nbj75vxu/) - - ``` html - - ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/25v08paf/) - - > By default, 8 hard-coded resolutions are populated as options. You can show only a custom set of options by hardcoding them. - - ``` html - - ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/tnfjks4q/) - - > Generally, you need to provide a resolution that the camera supports. However, in case a camera does not support the specified resolution, it usually uses the nearest supported resolution. As a result, the selected resolution may not be the actual resolution used. In this case, add an option with the class name `dbrScanner-opt-gotResolution` (as shown above) and the library will then use it to show the actual resolution. - -Interested to test it further? Read on to learn how to request a 30-day free trial. - -## Requesting A Trial - -Since v8.2.5, a free public trial license is used by default if no license is specified. - -> Network connection is required for the free public trial license to work. - -After that, if you want to evaluate the library further, you can [register for a Dynamsoft account](https://www.dynamsoft.com/api-common/Regist/Regist) (if you haven't already done so) and request a 30-day trial license via the Request a Trial License link. - -* If you like, you can also [contact our support team](https://www.dynamsoft.com/contact/) to get a trial extension. - -## System Requirements - -This library requires the following features which are supported by all modern mainstream browsers: - -* `WebAssembly`, `Blob`, `URL`/`createObjectURL`, `Web Workers` - - These four features are required for the library to work. - -* `MediaDevices`/`getUserMedia` - - This API is only required for in-browser video streaming. If a browser does not support this API, the [Single Frame Mode](https://www.dynamsoft.com/barcode-reader/programming/javascript/api-reference/BarcodeScanner/properties.html?ver=latest#singleframemode) will be used automatically. If the API exists but doesn't work correctly, the Single Frame Mode can be used as an alternative way to access the camera. - -The following table is a list of supported browsers based on the above requirements: - -Browser Name | Version -:-: | :-: -Chrome | v57+ (v59+ on Android/iOS1) -Firefox | v52+ (v55+ on Android/iOS1) -Edge2 | v16+ -Safari3 | v11+ - -1 iOS 14.3+ is required for camera video streaming in Chrome and Firefox or Apps using webviews. - -2 On Edge, due to strict Same-origin policy, you must host the library files on the same domain as your web page. - -3 Safari 11.2.2 ~ 11.2.6 are not supported. - -Apart from the browsers, the operating systems may impose some limitations of their own that could restrict the use of the library. Browser compatibility ultimately depends on whether the browser on that particular operating system supports the features listed above. - -## Hosting the library - -### Step One: Deploy the dist folder - -Once you have downloaded the library, you can locate the "dist" directory and copy it to your server (usually as part of your website / web application). The following shows some of the files in this directory: - -* `dbr.js` // The main library file -* `dbr.browser.mjs` // For using the library as a module (` -``` - -Optionally, you may also need to (specify the location of the "engine" files)[#specify-the-location-of-the-engine-files]. - - -## Advanced Usage - -In addition to the content mentioned above, the library has many other settings and options that you can adjust to best suit your usage. To read more, please see [advanced usage](https://www.dynamsoft.com/barcode-reader/programming/javascript/user-guide/advanced-usage.html?ver=latest). - -## How to Upgrade - -If you are using an older version of the library and want to upgrade it to the latest version, please read more on [how to upgrade](https://www.dynamsoft.com/barcode-reader/programming/javascript/user-guide/upgrade.html?ver=latest). - -## FAQ - -### Can I open the web page directly from the hard drive? - -Yes, for simple testing purposes, it's perfectly fine to open the file directly from the hard drive. However, you might encounter some issues in doing so (like unable to access the camera, etc.). The recommendation is to deploy this page to your web server and run it over **HTTPS**. If you don't have a ready-to-use web server but have a package manager like *npm* or *yarn*, you can set up a simple HTTP server in minutes. Check out [http-server on npm](https://www.npmjs.com/package/http-server) or [yarn](https://yarnpkg.com/package/http-server). - -### Why can't I use my camera? - -If you open the web page as `file:///` or `http://`, the camera may not work and you see the following error in 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 equivalent error is: - -> Trying to call getUserMedia from an insecure document. - -You get this error because the API [getUserMedia](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia) requires HTTPS to access the camera. - -* If you use Chrome or Firefox, you might not get the error because these two browsers allow camera access via file:/// and http://localhost. - -To make sure your web application can access the camera, please configure your web server to support HTTPS. The following links may help. - - - NGINX: [Configuring HTTPS servers](https://nginx.org/en/docs/http/configuring_https_servers.html) - - IIS: [Create a Self Signed Certificate in IIS](https://aboutssl.org/how-to-create-a-self-signed-certificate-in-iis/) - - Tomcat: [Setting Up SSL on Tomcat in 5 minutes](https://dzone.com/articles/setting-ssl-tomcat-5-minutes) - - Node.js: [npm tls](https://nodejs.org/docs/v0.4.1/api/tls.html) diff --git a/programming-old/javascript/user-guide/index-v8.6.0.md b/programming-old/javascript/user-guide/index-v8.6.0.md deleted file mode 100644 index 1d7d018e..00000000 --- a/programming-old/javascript/user-guide/index-v8.6.0.md +++ /dev/null @@ -1,508 +0,0 @@ ---- -layout: default-layout -title: v8.6.0 User Guide - Dynamsoft Barcode Reader JavaScript Edition -description: This is the user guide of Dynamsoft Barcode Reader JavaScript SDK. -keywords: user guide, javascript, js -breadcrumbText: User Guide -noTitleIndex: true -needGenerateH3Content: true -needAutoGenerateSidebar: true -permalink: /programming/javascript/user-guide/index-v8.6.0.html ---- - -# Dynamsoft Barcode Reader for Your Website - -Turn your web page into a barcode scanner with just a few lines of code. - -![version](https://img.shields.io/npm/v/dynamsoft-javascript-barcode.svg) -![downloads](https://img.shields.io/npm/dm/dynamsoft-javascript-barcode.svg) -![jsdelivr](https://img.shields.io/jsdelivr/npm/hm/dynamsoft-javascript-barcode.svg) -![](https://img.shields.io/snyk/vulnerabilities/npm/dynamsoft-javascript-barcode.svg) - -[![](https://img.shields.io/badge/Download-Offline%20SDK-orange)](https://www.dynamsoft.com/barcode-reader/downloads/?utm_source=github&product=dbr&package=js) - -Once integrated, your users can open your website in a browser, access their cameras and read barcodes directly from the video input. - -In this guide, you will learn step by step on how to integrate this library into your website. - -> For back-end barcode reading with Node.js, see [Dynamsoft Barcode Reader for Node](https://github.com/Dynamsoft/javascript-barcode/blob/master/README.NODE.md). - -**Table of Contents** - -* [Hello World - Simplest Implementation](#hello-world---simplest-implementation) -* [Building your own page](#building-your-own-page) - - [Include the library](#include-the-library) - - [Configure the library](#configure-the-library) - - [Interact with the library](#interact-with-the-library) -* [Requesting A Trial](#requesting-a-trial) -* [System Requirements](#system-requirements) -* [Hosting the Library](#hosting-the-library) -* [Advanced Usage](#advanced-usage) -* [How to Upgrade](#how-to-upgrade) -* [FAQ](#faq) - -**Popular Examples** - -* [Use the library in Angular](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/helloworld-angular.html?ver=latest&utm_source=github) -* [Use the library in React](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/helloworld-reactjs.html?ver=latest&utm_source=github) -* [Use the library in Vue](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/helloworld-vuejs.html?ver=latest&utm_source=github) - -You can also: - -* [Try All Online Examples](https://demo.dynamsoft.com/Samples/DBR/JS/index.html) -* [Try the Official Demo](https://demo.dynamsoft.com/barcode-reader-js?utm_source=github) - -## Hello World - Simplest Implementation - -Let's start by testing the "Hello World" example of the library which demonstrates how to use the minimum code to enable a web page to read barcodes from a live video stream. - -* Basic Requirements - + Internet connection - + [A supported browser](#system-requirements) - + Camera access - -### Step One: Check the code of the example - -The complete code of the "Hello World" example is shown below - -``` html - - - - - - - - - -``` - -> You can also find the code (with more comments) [on GitHub](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/master/1.hello-world/1.minimum-code.html). - -*About the code* - - + `createInstance()`: This method creates a `BarcodeScanner` object. This object can read barcodes directly from a video input with the help of its interactive UI (hidden by default) and the [MediaDevices interface](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices). - - + `onFrameRead`: This event is triggered every time the library finishes scanning a video frame. The `results` object contains all the barcode results that the library have found on this frame. In this example, we print the results to the browser console. - - + `onUnduplicatedRead`: This event is triggered when the library finds a new barcode, which is not a duplicate among multiple frames. `txt` holds the barcode text value while `result` is an object that holds details of the barcode. In this example, an alert will be displayed for this new barcode. - - + `show()`: This method brings up the built-in UI of the `BarcodeScanner` object. - -### Step Two: Test the example - -You can choose one of three ways to test the example: - -* [Hello World example - online](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/1.minimum-code.html) -* [Hello World example via JSFiddle](https://jsfiddle.net/DynamsoftTeam/pL4e7yrd/) -* [Download a copy](https://tst.dynamsoft.com/public/download/dbr/browser/code/helloworld.zip) of the example code and set it up locally - -Either way, you open the example page in a browser, allow the page to access your camera and the video will show up on the page. After that, you can point the camera at something with a barcode to read it. - -If the barcode is decoded, an alert will pop up with the result text. At the same time, the barcode location will be highlighted in the video feed. - - > For first use, you may need to wait a few seconds for the library to initialize. - -*Note*: - - + The library only scans a new frame when it has finished scanning the previous frame. The interval between two consecutive frames might not be enough time for the library to process the 1st frame (for 30 FPS, the interval is about 33 ms), therefore, not all frames are scanned. - - + The library requires a license to work. However, when no license is specified in the code, a [free public trial license](https://www.dynamsoft.com/license-server/docs/about/terms.html?ver=latest#public-trial-license?utm_source=guide) will automatically be used during which you can make initial evaluation of the library to decide whether or not you want to evaluate it further. If you do, you can [request a private trial license](#requesting-a-trial). - - > Network connection is required for the free public trial license to work. - -If the test doesn't go as expected, you can check out the [FAQ](#faq) or [contact us](https://www.dynamsoft.com/contact/?utm_source=github). - -## Building your own page - -### Include the library - -#### Use a CDN - -The simplest way to include the library is to use either the [jsDelivr](https://jsdelivr.com/) or [UNPKG](https://unpkg.com/) CDN. The "hello world" example above uses **jsDelivr**. - -* jsDelivr - - ``` html - - ``` - -* UNPKG - - ``` html - - ``` - -#### Host the library yourself (recommended) - -Besides using the CDN, you can also download the library and host its files on your own website / server before including it in your application. - -The following shows a few ways to download the library. - -* From the website - - [Download the JavaScript Package](https://www.dynamsoft.com/barcode-reader/downloads/?utm_source=github) - -* yarn - - ```cmd - $ yarn add dynamsoft-javascript-barcode - ``` - -* npm - - ``` - $ npm install dynamsoft-javascript-barcode --save - ``` - -Depending on how you downloaded the library and where you put it. You can typically include it like this: - -``` html - -``` - -or - -``` html - -``` - -Read more on [how to host the library](#hosting-the-library). - -### Configure the library - -Before using the library, you need to configure a few things. - -#### Specify the license - -The library requires a license to work, use the APIs `organizationID` and `handshakeCode` to specify how to acquire the license. - -``` javascript -Dynamsoft.DBR.BarcodeScanner.organizationID = "YOUR-ORGANIZATION-ID"; // Required. -Dynamsoft.DBR.BarcodeScanner.handshakeCode = "A-SPECIFIC-HANDSHAKECODE"; // Optional, if not specified, the default handshake code is used. -Dynamsoft.DBR.BarcodeScanner.sessionPassword = "PASSWORD-TO-PROTECT-YOUR-LICENSE"; // Optional but recomended, use it to protect your license. -Dynamsoft.DBR.BarcodeScanner.licenseServer = ["YOUR-OWN-MAIN-DLS", "YOUR-OWN-STANDBY-DLS"]; //Optional, ignore this line if you are using Dynamsoft-hosting DLS. - ``` - -*Note*: - -+ Network connection is required for the license to work. -+ If nothing is specified like the above "hello world" example, a [free public trial license](https://www.dynamsoft.com/license-server/docs/about/terms.html?ver=latest#public-trial-license?utm_source=guide) will be automatically used. -+ The license is actually fetched during the creation of a `BarcodeScanner` or `BarcodeReader` instance. -+ If a public network connection is not available, you can choose to host a license server in your private network. - -An alternative way to specify the license is to use an alphanumeric string which does not require a network connection. The following shows how it could be used. [Contact us](https://www.dynamsoft.com/contact/?utm_source=github) for more information. - -```javascript -Dynamsoft.DBR.BarcodeReader.productKeys = "t0068NQAAACgTVU2aucyxqETXKkiomqhV7YoLrnqjLiQQRSH5DBV1UtIs4..." -``` - -Or - -```html - -``` - -#### Specify the location of the "engine" files - -The "engine" files refer to *.worker.js, *.wasm.js and *.wasm, etc. which are loaded by the main library at runtime. This configuration option uses the API `engineResourcePath` and is often not required as these files usually are in the same location with the main library file (dbr.js). However, in cases where the engine files are not in the same location as the main library file (for example, with frameworks like Angular or React, dbr.js is compiled into another file), this configuration will be required. - -The following code uses the jsDelivr CDN, feel free to change it to your own location of these files. - -``` javascript -import DBR from "dynamsoft-javascript-barcode"; -DBR.BarcodeScanner.engineResourcePath = "https://cdn.jsdelivr.net/npm/dynamsoft-javascript-barcode@8.6.0/dist/"; -export default DBR; -``` - -### Interact with the library - -#### Create a `BarcodeScanner` object - -You can use one of two classes ( `BarcodeScanner` and `BarcodeReader` ) to interact with the library. `BarcodeReader` is a low-level class that processes images directly. `BarcodeScanner` , on the other hand, inherits from `BarcodeReader` and provides high-level APIs and a built-in GUI to allow continuous barcode scanning on video frames. We'll focus on `BarcodeScanner` in this guide. - -To use the library, we first create a `BarcodeScanner` object. - -``` javascript -try { - await Dynamsoft.DBR.BarcodeScanner.createInstance(); -} catch (ex) { - console.error(ex); -} -``` - -*Note*: - -* The creation of an object consists of two parallel tasks: one is to download and compile the "engine", the other is to fetch a license from Dynamsoft License Server (assuming an online license is used). - -#### Configure the `BarcodeScanner` object - -Let's take a look at the following code snippets first: - -``` javascript -// set which camera and what resolution to use -var allCameras = await scanner.getAllCameras(); -await scanner.setCurrentCamera(allCameras[0].deviceId); -await scanner.setResolution(1280, 720); -``` - -``` javascript -// set up the scanner behavior -let scanSettings = await scanner.getScanSettings(); -// disregard duplicated results found in a specified time period (in milliseconds) -scanSettings.duplicateForgetTime = 5000; -// set a scan interval in milliseconds so the library may release the CPU from time to time -scanSettings.intervalTime = 300; -await scanner.updateScanSettings(scanSettings); -``` - -``` javascript -// use one of the built-in RuntimeSetting templates: "single" (decode a single barcode, the default mode), "speed", "balance" and "coverage". -await scanner.updateRuntimeSettings("speed"); - -// make changes to the template. The code below demonstrates how to specify enabled symbologies -let runtimeSettings = await scanner.getRuntimeSettings(); -runtimeSettings.barcodeFormatIds = Dynamsoft.DBR.EnumBarcodeFormat.BF_ONED | Dynamsoft.DBR.EnumBarcodeFormat.BF_QR_CODE; -await scanner.updateRuntimeSettings(runtimeSettings); -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/yfkcajxz/) - -As you can see from the above code snippets, there are three types of configurations: - -* `get/updateVideoSettings`: Configures the data source, i.e., the camera. These settings include which camera to use, the resolution, etc. Learn more [here](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia#Syntax). - -* `get/updateScanSettings`: Configures the behavior of the scanner which includes `duplicateForgetTime`, `intervalTime` and `filter`, etc. - -* `get/updateRuntimeSettings`: Configures the decode engine. Find a full list of these settings and their corresponding descriptions [here](https://www.dynamsoft.com/barcode-reader/programming/javascript/api-reference/global-interfaces.html#runtimesettings?utm_source=github). For example, the following uses the built-in "speed" settings with updated `localizationModes`. - - ``` javascript - await barcodeScanner.updateRuntimeSettings("speed"); - //await barcodeScanner.updateRuntimeSettings("balance"); //alternative - //await barcodeScanner.updateRuntimeSettings("coverage"); //alternative - let settings = await barcodeScanner.getRuntimeSettings(); - settings.localizationModes = [ - Dynamsoft.DBR.EnumLocalizationMode.LM_CONNECTED_BLOCKS, - Dynamsoft.DBR.EnumLocalizationMode.LM_SCAN_DIRECTLY, - Dynamsoft.DBR.EnumLocalizationMode.LM_LINES, 0, 0, 0, 0, 0 - ]; - await barcodeScanner.updateRuntimeSettings(settings); - ``` - - Try in [JSFiddle](https://jsfiddle.net/DynamsoftTeam/f24h8c1m/). - - See also [settings samples](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/parameter-settings.html?ver=latest&utm_source=github). - -#### Customize the UI - -The built-in UI of the `BarcodeScanner` object is defined in the file `dist/dbr.scanner.html` . There are a few ways to customize it: - -* Modify the file `dist/dbr.scanner.html` directly. - - This option is only possible when you host this file on your own web server instead of using a CDN. - -* Copy the file `dist/dbr.scanner.html` to your application, modify it and use the the API `defaultUIElementURL` to set it as the default UI. - - ``` javascript - Dynamsoft.DBR.BarcodeScanner.defaultUIElementURL = "THE-URL-TO-THE-FILE"; - ``` - - > You must set `defaultUIElementURL` before you call `createInstance()` . - -* Append the default UI element to your page, customize it before showing it. - - ``` html -
- ``` - - ``` javascript - document.getElementById('scannerUI').appendChild(scanner.getUIElement()); - document.getElementsByClassName('dbrScanner-btn-close')[0].hidden = true; // Hide the close button - ``` - -* Build the UI element into your own web page and specify it with the API `setUIElement(HTMLElement)`. - - - Embed the video - - ``` html -
- -
- - ``` - - > The video element must have the class `dbrScanner-video` . - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/2jzeq1r6/) - - - Add the camera list and resolution list - - If the class names for these lists match the default ones, `dbrScanner-sel-camera` and `dbrScanner-sel-resolution` , the library will automatically populate the lists and handle the camera/resolution switching. - - ``` html - - ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/nbj75vxu/) - - ``` html - - ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/25v08paf/) - - > By default, 8 hard-coded resolutions are populated as options. You can show only a custom set of options by hardcoding them. - - ``` html - - ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/tnfjks4q/) - - > Generally, you need to provide a resolution that the camera supports. However, in case a camera does not support the specified resolution, it usually uses the nearest supported resolution. As a result, the selected resolution may not be the actual resolution used. In this case, add an option with the class name `dbrScanner-opt-gotResolution` (as shown above) and the library will then use it to show the actual resolution. - -See also [UI customization samples](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/ui-customization.html?ver=latest&utm_source=github). - -Interested to test it further? Read on to learn how to request a 30-day free trial. - -## Requesting A Trial - -Since v8.2.5, a free public trial license is used by default if no license is specified. - -> Network connection is required for the free public trial license to work. - -After that, if you want to evaluate the library further, you can [register for a Dynamsoft account](https://www.dynamsoft.com/api-common/Regist/Regist) (if you haven't already done so) and request a 30-day trial license via the Request a Trial License link. - -* If you like, you can also [contact our support team](https://www.dynamsoft.com/contact/?utm_source=github) to get a trial license. - -## System Requirements - -This library requires the following features which are supported by all modern mainstream browsers: - -* `WebAssembly`, `Blob`, `URL`/`createObjectURL`, `Web Workers` - - The above four features are required for the library to work. - -* `MediaDevices`/`getUserMedia` - - This API is only required for in-browser video streaming. If a browser does not support this API, the [Single Frame Mode](https://www.dynamsoft.com/barcode-reader/programming/javascript/api-reference/BarcodeScanner/properties.html?ver=latest&utm_source=github#singleframemode) will be used automatically. If the API exists but doesn't work correctly, the Single Frame Mode can be used as an alternative way to access the camera. - -The following table is a list of supported browsers based on the above requirements: - - Browser Name | Version - :-: | :-: - Chrome | v57+ (v59+ on Android/iOS1) - Firefox | v52+ (v55+ on Android/iOS1) - Edge2 | v16+ - Safari3 | v11+ - - 1 iOS 14.3+ is required for camera video streaming in Chrome and Firefox or Apps using webviews. - - 2 On Edge, due to strict Same-origin policy, you must host the library files on the same domain as your web page. - - 3 Safari 11.2.2 ~ 11.2.6 are not supported. - -Apart from the browsers, the operating systems may impose some limitations of their own that could restrict the use of the library. Browser compatibility ultimately depends on whether the browser on that particular operating system supports the features listed above. - -## Hosting the library - -### Step One: Deploy the dist folder - -Once you have downloaded the library, you can locate the "dist" directory and copy it to your server (usually as part of your website / web application). The following shows some of the files in this directory: - -* `dbr.js` // The main library file -* `dbr.browser.mjs` // For using the library as a module (` -``` - -Optionally, you may also need to (specify the location of the "engine" files)[#specify-the-location-of-the-engine-files]. - -## Advanced Usage - -In addition to the content mentioned above, the library has many other settings and options that you can adjust to best suit your usage. To read more, please see [advanced usage](https://www.dynamsoft.com/barcode-reader/programming/javascript/user-guide/advanced-usage.html?ver=latest&utm_source=github). - -## How to Upgrade - -If you are using an older version of the library and want to upgrade it to the latest version, please read more on [how to upgrade](https://www.dynamsoft.com/barcode-reader/programming/javascript/upgrade-guide/?ver=latest&utm_source=github). - -## FAQ - -### Can I open the web page directly from the hard drive? - -Yes, for simple testing purposes, it's perfectly fine to open the file directly from the hard drive. However, you might encounter some issues in doing so (like unable to access the camera, etc.). The recommendation is to deploy this page to your web server and run it over **HTTPS**. If you don't have a ready-to-use web server but have a package manager like *npm* or *yarn*, you can set up a simple HTTP server in minutes. Check out [http-server on npm](https://www.npmjs.com/package/http-server) or [yarn](https://yarnpkg.com/package/http-server). - -### Why can't I use my camera? - -If you open the web page as `file:///` or `http://`, the camera may not work and you see the following error in 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 equivalent error is: - -> Trying to call getUserMedia from an insecure document. - -You get this error because the API [getUserMedia](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia) requires HTTPS to access the camera. - -* If you use Chrome or Firefox, you might not get the error because these two browsers allow camera access via file:/// and http://localhost. - -To make sure your web application can access the camera, please configure your web server to support HTTPS. The following links may help. - - - NGINX: [Configuring HTTPS servers](https://nginx.org/en/docs/http/configuring_https_servers.html) - - IIS: [Create a Self Signed Certificate in IIS](https://aboutssl.org/how-to-create-a-self-signed-certificate-in-iis/) - - Tomcat: [Setting Up SSL on Tomcat in 5 minutes](https://dzone.com/articles/setting-ssl-tomcat-5-minutes) - - Node.js: [npm tls](https://nodejs.org/docs/v0.4.1/api/tls.html) diff --git a/programming-old/javascript/user-guide/index-v8.6.3.md b/programming-old/javascript/user-guide/index-v8.6.3.md deleted file mode 100644 index ff787d6e..00000000 --- a/programming-old/javascript/user-guide/index-v8.6.3.md +++ /dev/null @@ -1,508 +0,0 @@ ---- -layout: default-layout -title: v8.6.3 User Guide - Dynamsoft Barcode Reader JavaScript Edition -description: This is the user guide of Dynamsoft Barcode Reader JavaScript SDK. -keywords: user guide, javascript, js -breadcrumbText: User Guide -noTitleIndex: true -needGenerateH3Content: true -needAutoGenerateSidebar: true -permalink: /programming/javascript/user-guide/index-v8.6.3.html ---- - -# Dynamsoft Barcode Reader for Your Website - -Turn your web page into a barcode scanner with just a few lines of code. - -![version](https://img.shields.io/npm/v/dynamsoft-javascript-barcode.svg) -![downloads](https://img.shields.io/npm/dm/dynamsoft-javascript-barcode.svg) -![jsdelivr](https://img.shields.io/jsdelivr/npm/hm/dynamsoft-javascript-barcode.svg) -![](https://img.shields.io/snyk/vulnerabilities/npm/dynamsoft-javascript-barcode.svg) - -[![](https://img.shields.io/badge/Download-Offline%20SDK-orange)](https://www.dynamsoft.com/barcode-reader/downloads/?utm_source=github&product=dbr&package=js) - -Once integrated, your users can open your website in a browser, access their cameras and read barcodes directly from the video input. - -In this guide, you will learn step by step on how to integrate this library into your website. - -> For back-end barcode reading with Node.js, see [Dynamsoft Barcode Reader for Node](https://github.com/Dynamsoft/javascript-barcode/blob/main/README.NODE.md). - -**Table of Contents** - -* [Hello World - Simplest Implementation](#hello-world---simplest-implementation) -* [Building your own page](#building-your-own-page) - - [Include the library](#include-the-library) - - [Configure the library](#configure-the-library) - - [Interact with the library](#interact-with-the-library) -* [Requesting A Trial](#requesting-a-trial) -* [System Requirements](#system-requirements) -* [Hosting the Library](#hosting-the-library) -* [Advanced Usage](#advanced-usage) -* [How to Upgrade](#how-to-upgrade) -* [FAQ](#faq) - -**Popular Examples** - -* [Use the library in Angular](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/helloworld-angular.html?ver=latest&utm_source=github) -* [Use the library in React](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/helloworld-reactjs.html?ver=latest&utm_source=github) -* [Use the library in Vue](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/helloworld-vuejs.html?ver=latest&utm_source=github) - -You can also: - -* [Try All Online Examples](https://demo.dynamsoft.com/Samples/DBR/JS/index.html) -* [Try the Official Demo](https://demo.dynamsoft.com/barcode-reader-js?utm_source=github) - -## Hello World - Simplest Implementation - -Let's start by testing the "Hello World" example of the library which demonstrates how to use the minimum code to enable a web page to read barcodes from a live video stream. - -* Basic Requirements - + Internet connection - + [A supported browser](#system-requirements) - + Camera access - -### Step One: Check the code of the example - -The complete code of the "Hello World" example is shown below - -``` html - - - - - - - - - -``` - -> You can also find the code (with more comments) [on GitHub](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/master/1.hello-world/1.minimum-code.html). - -*About the code* - - + `createInstance()`: This method creates a `BarcodeScanner` object. This object can read barcodes directly from a video input with the help of its interactive UI (hidden by default) and the [MediaDevices interface](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices). - - + `onFrameRead`: This event is triggered every time the library finishes scanning a video frame. The `results` object contains all the barcode results that the library have found on this frame. In this example, we print the results to the browser console. - - + `onUnduplicatedRead`: This event is triggered when the library finds a new barcode, which is not a duplicate among multiple frames. `txt` holds the barcode text value while `result` is an object that holds details of the barcode. In this example, an alert will be displayed for this new barcode. - - + `show()`: This method brings up the built-in UI of the `BarcodeScanner` object. - -### Step Two: Test the example - -You can choose one of three ways to test the example: - -* [Hello World example - online](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/1.minimum-code.html) -* [Hello World example via JSFiddle](https://jsfiddle.net/DynamsoftTeam/pL4e7yrd/) -* [Download a copy](https://tst.dynamsoft.com/public/download/dbr/browser/code/helloworld.zip) of the example code and set it up locally - -Either way, you open the example page in a browser, allow the page to access your camera and the video will show up on the page. After that, you can point the camera at something with a barcode to read it. - -If the barcode is decoded, an alert will pop up with the result text. At the same time, the barcode location will be highlighted in the video feed. - - > For first use, you may need to wait a few seconds for the library to initialize. - -*Note*: - - + The library only scans a new frame when it has finished scanning the previous frame. The interval between two consecutive frames might not be enough time for the library to process the 1st frame (for 30 FPS, the interval is about 33 ms), therefore, not all frames are scanned. - - + The library requires a license to work. However, when no license is specified in the code, a [free public trial license](https://www.dynamsoft.com/license-server/docs/about/terms.html?ver=latest#public-trial-license?utm_source=guide) will automatically be used during which you can make initial evaluation of the library to decide whether or not you want to evaluate it further. If you do, you can [request a private trial license](#requesting-a-trial). - - > Network connection is required for the free public trial license to work. - -If the test doesn't go as expected, you can check out the [FAQ](#faq) or [contact us](https://www.dynamsoft.com/contact/?utm_source=github). - -## Building your own page - -### Include the library - -#### Use a CDN - -The simplest way to include the library is to use either the [jsDelivr](https://jsdelivr.com/) or [UNPKG](https://unpkg.com/) CDN. The "hello world" example above uses **jsDelivr**. - -* jsDelivr - - ``` html - - ``` - -* UNPKG - - ``` html - - ``` - -#### Host the library yourself (recommended) - -Besides using the CDN, you can also download the library and host its files on your own website / server before including it in your application. - -The following shows a few ways to download the library. - -* From the website - - [Download the JavaScript Package](https://www.dynamsoft.com/barcode-reader/downloads/?utm_source=github) - -* yarn - - ```cmd - $ yarn add dynamsoft-javascript-barcode - ``` - -* npm - - ``` - $ npm install dynamsoft-javascript-barcode --save - ``` - -Depending on how you downloaded the library and where you put it. You can typically include it like this: - -``` html - -``` - -or - -``` html - -``` - -Read more on [how to host the library](#hosting-the-library). - -### Configure the library - -Before using the library, you need to configure a few things. - -#### Specify the license - -The library requires a license to work, use the APIs `organizationID` and `handshakeCode` to specify how to acquire the license. - -``` javascript -Dynamsoft.DBR.BarcodeScanner.organizationID = "YOUR-ORGANIZATION-ID"; // Required. -Dynamsoft.DBR.BarcodeScanner.handshakeCode = "A-SPECIFIC-HANDSHAKECODE"; // Optional, if not specified, the default handshake code is used. -Dynamsoft.DBR.BarcodeScanner.sessionPassword = "PASSWORD-TO-PROTECT-YOUR-LICENSE"; // Optional but recomended, use it to protect your license. -Dynamsoft.DBR.BarcodeScanner.licenseServer = ["YOUR-OWN-MAIN-DLS", "YOUR-OWN-STANDBY-DLS"]; //Optional, ignore this line if you are using Dynamsoft-hosting DLS. - ``` - -*Note*: - -+ Network connection is required for the license to work. -+ If nothing is specified like the above "hello world" example, a [free public trial license](https://www.dynamsoft.com/license-server/docs/about/terms.html?ver=latest#public-trial-license?utm_source=guide) will be automatically used. -+ The license is actually fetched during the creation of a `BarcodeScanner` or `BarcodeReader` instance. -+ If a public network connection is not available, you can choose to host a license server in your private network. - -An alternative way to specify the license is to use an alphanumeric string which does not require a network connection. The following shows how it could be used. [Contact us](https://www.dynamsoft.com/contact/?utm_source=github) for more information. - -```javascript -Dynamsoft.DBR.BarcodeReader.productKeys = "t0068NQAAACgTVU2aucyxqETXKkiomqhV7YoLrnqjLiQQRSH5DBV1UtIs4..." -``` - -Or - -```html - -``` - -#### Specify the location of the "engine" files - -The "engine" files refer to *.worker.js, *.wasm.js and *.wasm, etc. which are loaded by the main library at runtime. This configuration option uses the API `engineResourcePath` and is often not required as these files usually are in the same location with the main library file (dbr.js). However, in cases where the engine files are not in the same location as the main library file (for example, with frameworks like Angular or React, dbr.js is compiled into another file), this configuration will be required. - -The following code uses the jsDelivr CDN, feel free to change it to your own location of these files. - -``` javascript -import DBR from "dynamsoft-javascript-barcode"; -DBR.BarcodeScanner.engineResourcePath = "https://cdn.jsdelivr.net/npm/dynamsoft-javascript-barcode@8.6.3/dist/"; -export default DBR; -``` - -### Interact with the library - -#### Create a `BarcodeScanner` object - -You can use one of two classes ( `BarcodeScanner` and `BarcodeReader` ) to interact with the library. `BarcodeReader` is a low-level class that processes images directly. `BarcodeScanner` , on the other hand, inherits from `BarcodeReader` and provides high-level APIs and a built-in GUI to allow continuous barcode scanning on video frames. We'll focus on `BarcodeScanner` in this guide. - -To use the library, we first create a `BarcodeScanner` object. - -``` javascript -try { - await Dynamsoft.DBR.BarcodeScanner.createInstance(); -} catch (ex) { - console.error(ex); -} -``` - -*Note*: - -* The creation of an object consists of two parallel tasks: one is to download and compile the "engine", the other is to fetch a license from Dynamsoft License Server (assuming an online license is used). - -#### Configure the `BarcodeScanner` object - -Let's take a look at the following code snippets first: - -``` javascript -// set which camera and what resolution to use -var allCameras = await scanner.getAllCameras(); -await scanner.setCurrentCamera(allCameras[0].deviceId); -await scanner.setResolution(1280, 720); -``` - -``` javascript -// set up the scanner behavior -let scanSettings = await scanner.getScanSettings(); -// disregard duplicated results found in a specified time period (in milliseconds) -scanSettings.duplicateForgetTime = 5000; -// set a scan interval in milliseconds so the library may release the CPU from time to time -scanSettings.intervalTime = 300; -await scanner.updateScanSettings(scanSettings); -``` - -``` javascript -// use one of the built-in RuntimeSetting templates: "single" (decode a single barcode, the default mode), "speed", "balance" and "coverage". -await scanner.updateRuntimeSettings("speed"); - -// make changes to the template. The code below demonstrates how to specify enabled symbologies -let runtimeSettings = await scanner.getRuntimeSettings(); -runtimeSettings.barcodeFormatIds = Dynamsoft.DBR.EnumBarcodeFormat.BF_ONED | Dynamsoft.DBR.EnumBarcodeFormat.BF_QR_CODE; -await scanner.updateRuntimeSettings(runtimeSettings); -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/yfkcajxz/) - -As you can see from the above code snippets, there are three types of configurations: - -* `get/updateVideoSettings`: Configures the data source, i.e., the camera. These settings include which camera to use, the resolution, etc. Learn more [here](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia#Syntax). - -* `get/updateScanSettings`: Configures the behavior of the scanner which includes `duplicateForgetTime`, `intervalTime` and `filter`, etc. - -* `get/updateRuntimeSettings`: Configures the decode engine. Find a full list of these settings and their corresponding descriptions [here](https://www.dynamsoft.com/barcode-reader/programming/javascript/api-reference/global-interfaces.html#runtimesettings?utm_source=github). For example, the following uses the built-in "speed" settings with updated `localizationModes`. - - ``` javascript - await barcodeScanner.updateRuntimeSettings("speed"); - //await barcodeScanner.updateRuntimeSettings("balance"); //alternative - //await barcodeScanner.updateRuntimeSettings("coverage"); //alternative - let settings = await barcodeScanner.getRuntimeSettings(); - settings.localizationModes = [ - Dynamsoft.DBR.EnumLocalizationMode.LM_CONNECTED_BLOCKS, - Dynamsoft.DBR.EnumLocalizationMode.LM_SCAN_DIRECTLY, - Dynamsoft.DBR.EnumLocalizationMode.LM_LINES, 0, 0, 0, 0, 0 - ]; - await barcodeScanner.updateRuntimeSettings(settings); - ``` - - Try in [JSFiddle](https://jsfiddle.net/DynamsoftTeam/f24h8c1m/). - - See also [settings samples](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/parameter-settings.html?ver=latest&utm_source=github). - -#### Customize the UI - -The built-in UI of the `BarcodeScanner` object is defined in the file `dist/dbr.scanner.html` . There are a few ways to customize it: - -* Modify the file `dist/dbr.scanner.html` directly. - - This option is only possible when you host this file on your own web server instead of using a CDN. - -* Copy the file `dist/dbr.scanner.html` to your application, modify it and use the the API `defaultUIElementURL` to set it as the default UI. - - ``` javascript - Dynamsoft.DBR.BarcodeScanner.defaultUIElementURL = "THE-URL-TO-THE-FILE"; - ``` - - > You must set `defaultUIElementURL` before you call `createInstance()` . - -* Append the default UI element to your page, customize it before showing it. - - ``` html -
- ``` - - ``` javascript - document.getElementById('scannerUI').appendChild(scanner.getUIElement()); - document.getElementsByClassName('dbrScanner-btn-close')[0].hidden = true; // Hide the close button - ``` - -* Build the UI element into your own web page and specify it with the API `setUIElement(HTMLElement)`. - - - Embed the video - - ``` html -
- -
- - ``` - - > The video element must have the class `dbrScanner-video` . - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/2jzeq1r6/) - - - Add the camera list and resolution list - - If the class names for these lists match the default ones, `dbrScanner-sel-camera` and `dbrScanner-sel-resolution` , the library will automatically populate the lists and handle the camera/resolution switching. - - ``` html - - ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/nbj75vxu/) - - ``` html - - ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/25v08paf/) - - > By default, 8 hard-coded resolutions are populated as options. You can show only a custom set of options by hardcoding them. - - ``` html - - ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/tnfjks4q/) - - > Generally, you need to provide a resolution that the camera supports. However, in case a camera does not support the specified resolution, it usually uses the nearest supported resolution. As a result, the selected resolution may not be the actual resolution used. In this case, add an option with the class name `dbrScanner-opt-gotResolution` (as shown above) and the library will then use it to show the actual resolution. - -See also [UI customization samples](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/ui-customization.html?ver=latest&utm_source=github). - -Interested to test it further? Read on to learn how to request a 30-day free trial. - -## Requesting A Trial - -Since v8.2.5, a free public trial license is used by default if no license is specified. - -> Network connection is required for the free public trial license to work. - -After that, if you want to evaluate the library further, you can [register for a Dynamsoft account](https://www.dynamsoft.com/api-common/Regist/Regist) (if you haven't already done so) and request a 30-day trial license via the Request a Trial License link. - -* If you like, you can also [contact our support team](https://www.dynamsoft.com/contact/?utm_source=github) to get a trial license. - -## System Requirements - -This library requires the following features which are supported by all modern mainstream browsers: - -* `WebAssembly`, `Blob`, `URL`/`createObjectURL`, `Web Workers` - - The above four features are required for the library to work. - -* `MediaDevices`/`getUserMedia` - - This API is only required for in-browser video streaming. If a browser does not support this API, the [Single Frame Mode](https://www.dynamsoft.com/barcode-reader/programming/javascript/api-reference/BarcodeScanner/properties.html?ver=latest&utm_source=github#singleframemode) will be used automatically. If the API exists but doesn't work correctly, the Single Frame Mode can be used as an alternative way to access the camera. - -The following table is a list of supported browsers based on the above requirements: - - Browser Name | Version - :-: | :-: - Chrome | v57+ (v59+ on Android/iOS1) - Firefox | v52+ (v55+ on Android/iOS1) - Edge2 | v16+ - Safari3 | v11+ - - 1 iOS 14.3+ is required for camera video streaming in Chrome and Firefox or Apps using webviews. - - 2 On Edge, due to strict Same-origin policy, you must host the library files on the same domain as your web page. - - 3 Safari 11.2.2 ~ 11.2.6 are not supported. - -Apart from the browsers, the operating systems may impose some limitations of their own that could restrict the use of the library. Browser compatibility ultimately depends on whether the browser on that particular operating system supports the features listed above. - -## Hosting the library - -### Step One: Deploy the dist folder - -Once you have downloaded the library, you can locate the "dist" directory and copy it to your server (usually as part of your website / web application). The following shows some of the files in this directory: - -* `dbr.js` // The main library file -* `dbr.browser.mjs` // For using the library as a module (` -``` - -Optionally, you may also need to [specify the location of the "engine" files](#specify-the-location-of-the-engine-files). - -## Advanced Usage - -In addition to the content mentioned above, the library has many other settings and options that you can adjust to best suit your usage. To read more, please see [advanced usage](https://www.dynamsoft.com/barcode-reader/programming/javascript/user-guide/advanced-usage.html?ver=latest&utm_source=github). - -## How to Upgrade - -If you are using an older version of the library and want to upgrade it to the latest version, please read more on [how to upgrade](https://www.dynamsoft.com/barcode-reader/programming/javascript/upgrade-guide/?ver=latest&utm_source=github). - -## FAQ - -### Can I open the web page directly from the hard drive? - -Yes, for simple testing purposes, it's perfectly fine to open the file directly from the hard drive. However, you might encounter some issues in doing so (like unable to access the camera, etc.). The recommendation is to deploy this page to your web server and run it over **HTTPS**. If you don't have a ready-to-use web server but have a package manager like *npm* or *yarn*, you can set up a simple HTTP server in minutes. Check out [http-server on npm](https://www.npmjs.com/package/http-server) or [yarn](https://yarnpkg.com/package/http-server). - -### Why can't I use my camera? - -If you open the web page as `file:///` or `http://`, the camera may not work and you see the following error in 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 equivalent error is: - -> Trying to call getUserMedia from an insecure document. - -You get this error because the API [getUserMedia](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia) requires HTTPS to access the camera. - -* If you use Chrome or Firefox, you might not get the error because these two browsers allow camera access via file:/// and http://localhost. - -To make sure your web application can access the camera, please configure your web server to support HTTPS. The following links may help. - - - NGINX: [Configuring HTTPS servers](https://nginx.org/en/docs/http/configuring_https_servers.html) - - IIS: [Create a Self Signed Certificate in IIS](https://aboutssl.org/how-to-create-a-self-signed-certificate-in-iis/) - - Tomcat: [Setting Up SSL on Tomcat in 5 minutes](https://dzone.com/articles/setting-ssl-tomcat-5-minutes) - - Node.js: [npm tls](https://nodejs.org/docs/v0.4.1/api/tls.html) diff --git a/programming-old/javascript/user-guide/index-v8.8.0.md b/programming-old/javascript/user-guide/index-v8.8.0.md deleted file mode 100644 index 4750dc81..00000000 --- a/programming-old/javascript/user-guide/index-v8.8.0.md +++ /dev/null @@ -1,508 +0,0 @@ ---- -layout: default-layout -title: v8.8.0 User Guide - Dynamsoft Barcode Reader JavaScript Edition -description: This is the user guide of Dynamsoft Barcode Reader JavaScript SDK. -keywords: user guide, javascript, js -breadcrumbText: User Guide -noTitleIndex: true -needGenerateH3Content: true -needAutoGenerateSidebar: true -permalink: /programming/javascript/user-guide/index-v8.8.0.html ---- - -# Dynamsoft Barcode Reader for Your Website - -Turn your web page into a barcode scanner with just a few lines of code. - -![version](https://img.shields.io/npm/v/dynamsoft-javascript-barcode.svg) -![downloads](https://img.shields.io/npm/dm/dynamsoft-javascript-barcode.svg) -![jsdelivr](https://img.shields.io/jsdelivr/npm/hm/dynamsoft-javascript-barcode.svg) -![](https://img.shields.io/snyk/vulnerabilities/npm/dynamsoft-javascript-barcode.svg) - -[![](https://img.shields.io/badge/Download-Offline%20SDK-orange)](https://www.dynamsoft.com/barcode-reader/downloads/?utm_source=github&product=dbr&package=js) - -Once integrated, your users can open your website in a browser, access their cameras and read barcodes directly from the video input. - -In this guide, you will learn step by step on how to integrate this library into your website. - -> For back-end barcode reading with Node.js, see [Dynamsoft Barcode Reader for Node](https://github.com/Dynamsoft/javascript-barcode/blob/main/README.NODE.md). - -**Table of Contents** - -* [Hello World - Simplest Implementation](#hello-world---simplest-implementation) -* [Building your own page](#building-your-own-page) - - [Include the library](#include-the-library) - - [Configure the library](#configure-the-library) - - [Interact with the library](#interact-with-the-library) -* [Requesting A Trial](#requesting-a-trial) -* [System Requirements](#system-requirements) -* [Hosting the Library](#hosting-the-library) -* [Advanced Usage](#advanced-usage) -* [How to Upgrade](#how-to-upgrade) -* [FAQ](#faq) - -**Popular Examples** - -* [Use the library in Angular](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/helloworld-angular.html?ver=latest&utm_source=github) -* [Use the library in React](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/helloworld-reactjs.html?ver=latest&utm_source=github) -* [Use the library in Vue](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/helloworld-vuejs.html?ver=latest&utm_source=github) - -You can also: - -* [Try All Online Examples](https://demo.dynamsoft.com/Samples/DBR/JS/index.html) -* [Try the Official Demo](https://demo.dynamsoft.com/barcode-reader-js?utm_source=github) - -## Hello World - Simplest Implementation - -Let's start by testing the "Hello World" example of the library which demonstrates how to use the minimum code to enable a web page to read barcodes from a live video stream. - -* Basic Requirements - + Internet connection - + [A supported browser](#system-requirements) - + Camera access - -### Step One: Check the code of the example - -The complete code of the "Hello World" example is shown below - -``` html - - - - - - - - - -``` - -> You can also find the code (with more comments) [on GitHub](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/master/1.hello-world/1.minimum-code.html). - -*About the code* - - + `createInstance()`: This method creates a `BarcodeScanner` object. This object can read barcodes directly from a video input with the help of its interactive UI (hidden by default) and the [MediaDevices interface](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices). - - + `onFrameRead`: This event is triggered every time the library finishes scanning a video frame. The `results` object contains all the barcode results that the library have found on this frame. In this example, we print the results to the browser console. - - + `onUnduplicatedRead`: This event is triggered when the library finds a new barcode, which is not a duplicate among multiple frames. `txt` holds the barcode text value while `result` is an object that holds details of the barcode. In this example, an alert will be displayed for this new barcode. - - + `show()`: This method brings up the built-in UI of the `BarcodeScanner` object. - -### Step Two: Test the example - -You can choose one of three ways to test the example: - -* [Hello World example - online](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/1.minimum-code.html) -* [Hello World example via JSFiddle](https://jsfiddle.net/DynamsoftTeam/pL4e7yrd/) -* [Download a copy](https://tst.dynamsoft.com/public/download/dbr/browser/code/helloworld.zip) of the example code and set it up locally - -Either way, you open the example page in a browser, allow the page to access your camera and the video will show up on the page. After that, you can point the camera at something with a barcode to read it. - -If the barcode is decoded, an alert will pop up with the result text. At the same time, the barcode location will be highlighted in the video feed. - - > For first use, you may need to wait a few seconds for the library to initialize. - -*Note*: - - + The library only scans a new frame when it has finished scanning the previous frame. The interval between two consecutive frames might not be enough time for the library to process the 1st frame (for 30 FPS, the interval is about 33 ms), therefore, not all frames are scanned. - - + The library requires a license to work. However, when no license is specified in the code, a [free public trial license](https://www.dynamsoft.com/license-server/docs/about/terms.html?ver=latest#public-trial-license?utm_source=guide) will automatically be used during which you can make initial evaluation of the library to decide whether or not you want to evaluate it further. If you do, you can [request a private trial license](#requesting-a-trial). - - > Network connection is required for the free public trial license to work. - -If the test doesn't go as expected, you can check out the [FAQ](#faq) or [contact us](https://www.dynamsoft.com/contact/?utm_source=github). - -## Building your own page - -### Include the library - -#### Use a CDN - -The simplest way to include the library is to use either the [jsDelivr](https://jsdelivr.com/) or [UNPKG](https://unpkg.com/) CDN. The "hello world" example above uses **jsDelivr**. - -* jsDelivr - - ``` html - - ``` - -* UNPKG - - ``` html - - ``` - -#### Host the library yourself (recommended) - -Besides using the CDN, you can also download the library and host its files on your own website / server before including it in your application. - -The following shows a few ways to download the library. - -* From the website - - [Download the JavaScript Package](https://www.dynamsoft.com/barcode-reader/downloads/?utm_source=github) - -* yarn - - ```cmd - $ yarn add dynamsoft-javascript-barcode - ``` - -* npm - - ``` - $ npm install dynamsoft-javascript-barcode --save - ``` - -Depending on how you downloaded the library and where you put it. You can typically include it like this: - -``` html - -``` - -or - -``` html - -``` - -Read more on [how to host the library](#hosting-the-library). - -### Configure the library - -Before using the library, you need to configure a few things. - -#### Specify the license - -The library requires a license to work, use the APIs `organizationID` and `handshakeCode` to specify how to acquire the license. - -``` javascript -Dynamsoft.DBR.BarcodeScanner.organizationID = "YOUR-ORGANIZATION-ID"; // Required. -Dynamsoft.DBR.BarcodeScanner.handshakeCode = "A-SPECIFIC-HANDSHAKECODE"; // Optional, if not specified, the default handshake code is used. -Dynamsoft.DBR.BarcodeScanner.sessionPassword = "PASSWORD-TO-PROTECT-YOUR-LICENSE"; // Optional but recomended, use it to protect your license. -Dynamsoft.DBR.BarcodeScanner.licenseServer = ["YOUR-OWN-MAIN-DLS", "YOUR-OWN-STANDBY-DLS"]; //Optional, ignore this line if you are using Dynamsoft-hosting DLS. - ``` - -*Note*: - -+ Network connection is required for the license to work. -+ If nothing is specified like the above "hello world" example, a [free public trial license](https://www.dynamsoft.com/license-server/docs/about/terms.html?ver=latest#public-trial-license?utm_source=guide) will be automatically used. -+ The license is actually fetched during the creation of a `BarcodeScanner` or `BarcodeReader` instance. -+ If a public network connection is not available, you can choose to host a license server in your private network. - -An alternative way to specify the license is to use an alphanumeric string which does not require a network connection. The following shows how it could be used. [Contact us](https://www.dynamsoft.com/contact/?utm_source=github) for more information. - -```javascript -Dynamsoft.DBR.BarcodeReader.productKeys = "t0068NQAAACgTVU2aucyxqETXKkiomqhV7YoLrnqjLiQQRSH5DBV1UtIs4..." -``` - -Or - -```html - -``` - -#### Specify the location of the "engine" files - -The "engine" files refer to *.worker.js, *.wasm.js and *.wasm, etc. which are loaded by the main library at runtime. This configuration option uses the API `engineResourcePath` and is often not required as these files usually are in the same location with the main library file (dbr.js). However, in cases where the engine files are not in the same location as the main library file (for example, with frameworks like Angular or React, dbr.js is compiled into another file), this configuration will be required. - -The following code uses the jsDelivr CDN, feel free to change it to your own location of these files. - -``` javascript -import DBR from "dynamsoft-javascript-barcode"; -DBR.BarcodeScanner.engineResourcePath = "https://cdn.jsdelivr.net/npm/dynamsoft-javascript-barcode@8.8.0/dist/"; -export default DBR; -``` - -### Interact with the library - -#### Create a `BarcodeScanner` object - -You can use one of two classes ( `BarcodeScanner` and `BarcodeReader` ) to interact with the library. `BarcodeReader` is a low-level class that processes images directly. `BarcodeScanner` , on the other hand, inherits from `BarcodeReader` and provides high-level APIs and a built-in GUI to allow continuous barcode scanning on video frames. We'll focus on `BarcodeScanner` in this guide. - -To use the library, we first create a `BarcodeScanner` object. - -``` javascript -try { - await Dynamsoft.DBR.BarcodeScanner.createInstance(); -} catch (ex) { - console.error(ex); -} -``` - -*Note*: - -* The creation of an object consists of two parallel tasks: one is to download and compile the "engine", the other is to fetch a license from Dynamsoft License Server (assuming an online license is used). - -#### Configure the `BarcodeScanner` object - -Let's take a look at the following code snippets first: - -``` javascript -// set which camera and what resolution to use -var allCameras = await scanner.getAllCameras(); -await scanner.setCurrentCamera(allCameras[0].deviceId); -await scanner.setResolution(1280, 720); -``` - -``` javascript -// set up the scanner behavior -let scanSettings = await scanner.getScanSettings(); -// disregard duplicated results found in a specified time period (in milliseconds) -scanSettings.duplicateForgetTime = 5000; -// set a scan interval in milliseconds so the library may release the CPU from time to time -scanSettings.intervalTime = 300; -await scanner.updateScanSettings(scanSettings); -``` - -``` javascript -// use one of the built-in RuntimeSetting templates: "single" (decode a single barcode, the default mode), "speed", "balance" and "coverage". -await scanner.updateRuntimeSettings("speed"); - -// make changes to the template. The code below demonstrates how to specify enabled symbologies -let runtimeSettings = await scanner.getRuntimeSettings(); -runtimeSettings.barcodeFormatIds = Dynamsoft.DBR.EnumBarcodeFormat.BF_ONED | Dynamsoft.DBR.EnumBarcodeFormat.BF_QR_CODE; -await scanner.updateRuntimeSettings(runtimeSettings); -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/yfkcajxz/) - -As you can see from the above code snippets, there are three types of configurations: - -* `get/updateVideoSettings`: Configures the data source, i.e., the camera. These settings include which camera to use, the resolution, etc. Learn more [here](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia#Syntax). - -* `get/updateScanSettings`: Configures the behavior of the scanner which includes `duplicateForgetTime`, `intervalTime` and `filter`, etc. - -* `get/updateRuntimeSettings`: Configures the decode engine. Find a full list of these settings and their corresponding descriptions [here](https://www.dynamsoft.com/barcode-reader/programming/javascript/api-reference/global-interfaces.html#runtimesettings?utm_source=github). For example, the following uses the built-in "speed" settings with updated `localizationModes`. - - ``` javascript - await barcodeScanner.updateRuntimeSettings("speed"); - //await barcodeScanner.updateRuntimeSettings("balance"); //alternative - //await barcodeScanner.updateRuntimeSettings("coverage"); //alternative - let settings = await barcodeScanner.getRuntimeSettings(); - settings.localizationModes = [ - Dynamsoft.DBR.EnumLocalizationMode.LM_CONNECTED_BLOCKS, - Dynamsoft.DBR.EnumLocalizationMode.LM_SCAN_DIRECTLY, - Dynamsoft.DBR.EnumLocalizationMode.LM_LINES, 0, 0, 0, 0, 0 - ]; - await barcodeScanner.updateRuntimeSettings(settings); - ``` - - Try in [JSFiddle](https://jsfiddle.net/DynamsoftTeam/f24h8c1m/). - - See also [settings samples](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/parameter-settings.html?ver=latest&utm_source=github). - -#### Customize the UI - -The built-in UI of the `BarcodeScanner` object is defined in the file `dist/dbr.scanner.html` . There are a few ways to customize it: - -* Modify the file `dist/dbr.scanner.html` directly. - - This option is only possible when you host this file on your own web server instead of using a CDN. - -* Copy the file `dist/dbr.scanner.html` to your application, modify it and use the the API `defaultUIElementURL` to set it as the default UI. - - ``` javascript - Dynamsoft.DBR.BarcodeScanner.defaultUIElementURL = "THE-URL-TO-THE-FILE"; - ``` - - > You must set `defaultUIElementURL` before you call `createInstance()` . - -* Append the default UI element to your page, customize it before showing it. - - ``` html -
- ``` - - ``` javascript - document.getElementById('scannerUI').appendChild(scanner.getUIElement()); - document.getElementsByClassName('dbrScanner-btn-close')[0].hidden = true; // Hide the close button - ``` - -* Build the UI element into your own web page and specify it with the API `setUIElement(HTMLElement)`. - - - Embed the video - - ``` html -
- -
- - ``` - - > The video element must have the class `dbrScanner-video` . - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/2jzeq1r6/) - - - Add the camera list and resolution list - - If the class names for these lists match the default ones, `dbrScanner-sel-camera` and `dbrScanner-sel-resolution` , the library will automatically populate the lists and handle the camera/resolution switching. - - ``` html - - ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/nbj75vxu/) - - ``` html - - ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/25v08paf/) - - > By default, 8 hard-coded resolutions are populated as options. You can show only a custom set of options by hardcoding them. - - ``` html - - ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/tnfjks4q/) - - > Generally, you need to provide a resolution that the camera supports. However, in case a camera does not support the specified resolution, it usually uses the nearest supported resolution. As a result, the selected resolution may not be the actual resolution used. In this case, add an option with the class name `dbrScanner-opt-gotResolution` (as shown above) and the library will then use it to show the actual resolution. - -See also [UI customization samples](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/ui-customization.html?ver=latest&utm_source=github). - -Interested to test it further? Read on to learn how to request a 30-day free trial. - -## Requesting A Trial - -Since v8.2.5, a free public trial license is used by default if no license is specified. - -> Network connection is required for the free public trial license to work. - -After that, if you want to evaluate the library further, you can [register for a Dynamsoft account](https://www.dynamsoft.com/api-common/Regist/Regist) (if you haven't already done so) and request a 30-day trial license via the Request a Trial License link. - -* If you like, you can also [contact our support team](https://www.dynamsoft.com/contact/?utm_source=github) to get a trial license. - -## System Requirements - -This library requires the following features which are supported by all modern mainstream browsers: - -* `WebAssembly`, `Blob`, `URL`/`createObjectURL`, `Web Workers` - - The above four features are required for the library to work. - -* `MediaDevices`/`getUserMedia` - - This API is only required for in-browser video streaming. If a browser does not support this API, the [Single Frame Mode](https://www.dynamsoft.com/barcode-reader/programming/javascript/api-reference/BarcodeScanner/properties.html?ver=latest&utm_source=github#singleframemode) will be used automatically. If the API exists but doesn't work correctly, the Single Frame Mode can be used as an alternative way to access the camera. - -The following table is a list of supported browsers based on the above requirements: - - Browser Name | Version - :-: | :-: - Chrome | v57+ (v59+ on Android/iOS1) - Firefox | v52+ (v55+ on Android/iOS1) - Edge2 | v16+ - Safari3 | v11+ - - 1 iOS 14.3+ is required for camera video streaming in Chrome and Firefox or Apps using webviews. - - 2 On Edge, due to strict Same-origin policy, you must host the library files on the same domain as your web page. - - 3 Safari 11.2.2 ~ 11.2.6 are not supported. - -Apart from the browsers, the operating systems may impose some limitations of their own that could restrict the use of the library. Browser compatibility ultimately depends on whether the browser on that particular operating system supports the features listed above. - -## Hosting the library - -### Step One: Deploy the dist folder - -Once you have downloaded the library, you can locate the "dist" directory and copy it to your server (usually as part of your website / web application). The following shows some of the files in this directory: - -* `dbr.js` // The main library file -* `dbr.browser.mjs` // For using the library as a module (` -``` - -Optionally, you may also need to [specify the location of the "engine" files](#specify-the-location-of-the-engine-files). - -## Advanced Usage - -In addition to the content mentioned above, the library has many other settings and options that you can adjust to best suit your usage. To read more, please see [advanced usage](https://www.dynamsoft.com/barcode-reader/programming/javascript/user-guide/advanced-usage.html?ver=latest&utm_source=github). - -## How to Upgrade - -If you are using an older version of the library and want to upgrade it to the latest version, please read more on [how to upgrade](https://www.dynamsoft.com/barcode-reader/programming/javascript/upgrade-guide/?ver=latest&utm_source=github). - -## FAQ - -### Can I open the web page directly from the hard drive? - -Yes, for simple testing purposes, it's perfectly fine to open the file directly from the hard drive. However, you might encounter some issues in doing so (like unable to access the camera, etc.). The recommendation is to deploy this page to your web server and run it over **HTTPS**. If you don't have a ready-to-use web server but have a package manager like *npm* or *yarn*, you can set up a simple HTTP server in minutes. Check out [http-server on npm](https://www.npmjs.com/package/http-server) or [yarn](https://yarnpkg.com/package/http-server). - -### Why can't I use my camera? - -If you open the web page as `file:///` or `http://`, the camera may not work and you see the following error in 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 equivalent error is: - -> Trying to call getUserMedia from an insecure document. - -You get this error because the API [getUserMedia](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia) requires HTTPS to access the camera. - -* If you use Chrome or Firefox, you might not get the error because these two browsers allow camera access via file:/// and http://localhost. - -To make sure your web application can access the camera, please configure your web server to support HTTPS. The following links may help. - - - NGINX: [Configuring HTTPS servers](https://nginx.org/en/docs/http/configuring_https_servers.html) - - IIS: [Create a Self Signed Certificate in IIS](https://aboutssl.org/how-to-create-a-self-signed-certificate-in-iis/) - - Tomcat: [Setting Up SSL on Tomcat in 5 minutes](https://dzone.com/articles/setting-ssl-tomcat-5-minutes) - - Node.js: [npm tls](https://nodejs.org/docs/v0.4.1/api/tls.html) diff --git a/programming-old/javascript/user-guide/index-v8.8.3.md b/programming-old/javascript/user-guide/index-v8.8.3.md deleted file mode 100644 index 48515fd3..00000000 --- a/programming-old/javascript/user-guide/index-v8.8.3.md +++ /dev/null @@ -1,527 +0,0 @@ ---- -layout: default-layout -title: v8.8.3 User Guide - Dynamsoft Barcode Reader JavaScript Edition -description: This is the user guide of Dynamsoft Barcode Reader JavaScript SDK. -keywords: user guide, javascript, js -breadcrumbText: User Guide -noTitleIndex: true -needGenerateH3Content: true -needAutoGenerateSidebar: true -permalink: /programming/javascript/user-guide/index-v8.8.3.html ---- - -# Dynamsoft Barcode Reader for Your Website - -Turn your web page into a barcode scanner with just a few lines of code. - -![version](https://img.shields.io/npm/v/dynamsoft-javascript-barcode.svg) -![downloads](https://img.shields.io/npm/dm/dynamsoft-javascript-barcode.svg) -![jsdelivr](https://img.shields.io/jsdelivr/npm/hm/dynamsoft-javascript-barcode.svg) -![](https://img.shields.io/snyk/vulnerabilities/npm/dynamsoft-javascript-barcode.svg) - -[![](https://img.shields.io/badge/Download-Offline%20SDK-orange)](https://www.dynamsoft.com/barcode-reader/downloads/?utm_source=guide&product=dbr&package=js) - -Once integrated, your users can open your website in a browser, access their cameras and read barcodes directly from the video input. - -In this guide, you will learn step by step on how to integrate this library into your website. - -[TEST THE LIBRARY](https://www.dynamsoft.com/barcode-reader/downloads/?utm_source=guide&product=dbr&package=js) - -> For back-end barcode reading with Node.js, see [Dynamsoft Barcode Reader for Node](https://github.com/Dynamsoft/javascript-barcode/blob/main/README.NODE.md). - -**Table of Contents** - -* [Hello World - Simplest Implementation](#hello-world---simplest-implementation) -* [Building your own page](#building-your-own-page) - - [Include the library](#include-the-library) - - [Configure the library](#configure-the-library) - - [Interact with the library](#interact-with-the-library) -* [Requesting A Trial](#requesting-a-trial) -* [System Requirements](#system-requirements) -* [Hosting the Library](#hosting-the-library) -* [Advanced Usage](#advanced-usage) -* [How to Upgrade](#how-to-upgrade) -* [FAQ](#faq) - -**Popular Examples** - -* [Basic Implementation](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/helloworld-mincode.html?ver=latest&utm_source=guide) -* [Use the library in Angular](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/helloworld-angular.html?ver=latest&utm_source=guide) -* [Use the library in React](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/helloworld-reactjs.html?ver=latest&utm_source=guide) -* [Use the library in Vue](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/helloworld-vuejs.html?ver=latest&utm_source=guide) -* [Use the library in a PWA APP](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/helloworld-pwa.html?ver=latest&utm_source=guide) - -You can also: - -* [Try All Online Examples](https://demo.dynamsoft.com/Samples/DBR/JS/index.html?utm_source=guide) -* [Try the Official Demo](https://demo.dynamsoft.com/barcode-reader-js/?utm_source=guide) - -## Hello World - Simplest Implementation - -Let's start by testing the "Hello World" example of the library which demonstrates how to use the minimum code to enable a web page to read barcodes from a live video stream. - -* Basic Requirements - + Internet connection - + [A supported browser](#system-requirements) - + Camera access - -### Step One: Check the code of the example - -The complete code of the "Hello World" example is shown below - -``` html - - - - - - - - - -``` - -> You can also find the code (with more comments) [on GitHub](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/master/1.hello-world/1.minimum-code.html?utm_source=guide). - -*About the code* - - + `createInstance()`: This method creates a `BarcodeScanner` object. This object can read barcodes directly from a video input with the help of its interactive UI (hidden by default) and the [MediaDevices interface](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices). - - + `onFrameRead`: This event is triggered every time the library finishes scanning a video frame. The `results` object contains all the barcode results that the library have found on this frame. In this example, we print the results to the browser console. - - + `onUnduplicatedRead`: This event is triggered when the library finds a new barcode, which is not a duplicate among multiple frames. `txt` holds the barcode text value while `result` is an object that holds details of the barcode. In this example, an alert will be displayed for this new barcode. - - + `show()`: This method brings up the built-in UI of the `BarcodeScanner` object and starts scanning. - -### Step Two: Test the example - -You can choose one of three ways to test the example: - -* [Hello World example - online](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/1.minimum-code.html?utm_source=guide) -* [Hello World example via JSFiddle](https://jsfiddle.net/DynamsoftTeam/pL4e7yrd/) -* [Download a copy](https://tst.dynamsoft.com/public/download/dbr/browser/code/helloworld.zip) of the example code and set it up locally - -Either way, you open the example page in a browser, allow the page to access your camera and the video will show up on the page. After that, you can point the camera at something with a barcode to read it. - -If the barcode is decoded, an alert will pop up with the result text. At the same time, the barcode location will be highlighted in the video feed. - - > For first use, you may need to wait a few seconds for the library to initialize. - -*Note*: - - + The library only scans a new frame when it has finished scanning the previous frame. The interval between two consecutive frames might not be enough time for the library to process the 1st frame (for 30 FPS, the interval is about 33 ms), therefore, not all frames are scanned. - - + The library requires a license to work. However, when no license is specified in the code, a [free public trial license](https://www.dynamsoft.com/license-server/docs/about/terms.html?ver=latest#public-trial-license?utm_source=guide) will automatically be used during which you can make initial evaluation of the library to decide whether or not you want to evaluate it further. If you do, you can [request a private trial license](#requesting-a-trial). - - > Network connection is required for the free public trial license to work. - -If the test doesn't go as expected, you can check out the [FAQ](#faq) or [contact us](https://www.dynamsoft.com/contact/?utm_source=guide). - -## Building your own page - -### Include the library - -#### Use a CDN - -The simplest way to include the library is to use either the [jsDelivr](https://jsdelivr.com/) or [UNPKG](https://unpkg.com/) CDN. The "hello world" example above uses **jsDelivr**. - -* jsDelivr - - ``` html - - ``` - -* UNPKG - - ``` html - - ``` - -#### Host the library yourself - -Besides using the CDN, you can also download the library and host its files on your own website / server before including it in your application. - -The following shows a few ways to download the library. - -* From the website - - [Download the JavaScript Package](https://www.dynamsoft.com/barcode-reader/downloads/?utm_source=guide) - -* yarn - - ```cmd - $ yarn add dynamsoft-javascript-barcode - ``` - -* npm - - ``` - $ npm install dynamsoft-javascript-barcode --save - ``` - -Depending on how you downloaded the library and where you put it. You can typically include it like this: - -``` html - -``` - -or - -``` html - -``` - -Read more on [how to host the library](#hosting-the-library). - -### Configure the library - -Before using the library, you need to configure a few things. - -#### Specify the license - -The library requires a license to work, use the APIs `organizationID` and / or `handshakeCode` to specify how to acquire the license. - -``` javascript -Dynamsoft.DBR.BarcodeScanner.organizationID = "YOUR-ORGANIZATION-ID"; // Required. -Dynamsoft.DBR.BarcodeScanner.handshakeCode = "A-SPECIFIC-HANDSHAKECODE"; // Optional, if not specified, the default handshake code is used. -Dynamsoft.DBR.BarcodeScanner.sessionPassword = "PASSWORD-TO-PROTECT-YOUR-LICENSE"; // Optional but recomended, use it to protect your license. -Dynamsoft.DBR.BarcodeScanner.licenseServer = ["YOUR-OWN-MAIN-DLS", "YOUR-OWN-STANDBY-DLS"]; //Optional, ignore this line if you are using Dynamsoft-hosting DLS. -``` - -*Note*: - -+ Network connection is required for the license to work. -+ If nothing is specified like the above "hello world" example, a [free public trial license](https://www.dynamsoft.com/license-server/docs/about/terms.html?ver=latest#public-trial-license?utm_source=guide) will be automatically used. -+ The license is actually fetched during the creation of a `BarcodeScanner` or `BarcodeReader` instance. -+ If a public network connection is not available, you can choose to host a license server in your private network. [Contact us](https://www.dynamsoft.com/contact/?utm_source=guide) for more information. - -An alternative way to specify the license is to use an alphanumeric string which does not require a network connection. The following shows how it could be used. [Contact us](https://www.dynamsoft.com/contact/?utm_source=guide) for more information. - -```javascript -Dynamsoft.DBR.BarcodeReader.productKeys = "t0068NQAAACgTVU2aucyxqETXKkiomqhV7YoLrnqjLiQQRSH5DBV1UtIs4..." -``` - -Or - -```html - -``` - -#### Specify the location of the "engine" files - -The "engine" files refer to *.worker.js, *.wasm.js and *.wasm, etc. which are loaded by the main library at runtime. This configuration option uses the API `engineResourcePath` and is often not required as these files usually are in the same location with the main library file (dbr.js). However, in cases where the engine files are not in the same location as the main library file (for example, with frameworks like Angular or React, dbr.js is compiled into another file), this configuration will be required. - -The following code uses the jsDelivr CDN, feel free to change it to your own location of these files. - -``` javascript -Dynamsoft.DBR.BarcodeScanner.engineResourcePath = "https://cdn.jsdelivr.net/npm/dynamsoft-javascript-barcode@8.8.3/dist/"; -``` - -### Interact with the library - -#### Create a `BarcodeScanner` object - -You can use one of two classes ( `BarcodeScanner` and `BarcodeReader` ) to interact with the library. `BarcodeReader` is a low-level class that processes images directly. `BarcodeScanner` , on the other hand, inherits from `BarcodeReader` and provides high-level APIs and a built-in GUI to allow continuous barcode scanning on video frames. We'll focus on `BarcodeScanner` in this guide. - -To use the library, we first create a `BarcodeScanner` object. - -``` javascript -let scanner = null; -try { - scanner = await Dynamsoft.DBR.BarcodeScanner.createInstance(); -} catch (ex) { - console.error(ex); -} -``` - -When creating a `BarcodeScanner` object within a function which may be called more than once, it's best to use a "helper" variable to avoid double creation such as `pScanner` in the following code - -``` javascript -let scanner = null, pScanner = null; -function createBarcodeScanner(){ - try { - scanner = await (pScanner = pScanner || Dynamsoft.DBR.BarcodeScanner.createInstance()); - } catch (ex) { - console.error(ex); - } -} -``` - -*Note*: - -* The creation of an object consists of two parallel tasks: one is to download and compile the "engine", the other is to fetch a license from Dynamsoft License Server (assuming an online license is used). - -#### Configure the `BarcodeScanner` object - -Let's take a look at the following code snippets first: - -``` javascript -// set which camera and what resolution to use -var allCameras = await scanner.getAllCameras(); -await scanner.setCurrentCamera(allCameras[0].deviceId); -await scanner.setResolution(1280, 720); -``` - -``` javascript -// set up the scanner behavior -let scanSettings = await scanner.getScanSettings(); -// disregard duplicated results found in a specified time period (in milliseconds) -scanSettings.duplicateForgetTime = 5000; -// set a scan interval in milliseconds so the library may release the CPU from time to time -scanSettings.intervalTime = 300; -await scanner.updateScanSettings(scanSettings); -``` - -``` javascript -// use one of the built-in RuntimeSetting templates: "single" (decode a single barcode, the default mode), "speed", "balance" and "coverage" -await scanner.updateRuntimeSettings("speed"); - -// make changes to the template. The code below demonstrates how to specify enabled symbologies -let runtimeSettings = await scanner.getRuntimeSettings(); -runtimeSettings.barcodeFormatIds = Dynamsoft.DBR.EnumBarcodeFormat.BF_ONED | Dynamsoft.DBR.EnumBarcodeFormat.BF_QR_CODE; -await scanner.updateRuntimeSettings(runtimeSettings); -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/yfkcajxz/) - -As you can see from the above code snippets, there are three types of configurations: - -* `get/updateVideoSettings`: Configures the data source, i.e., the camera. These settings include which camera to use, the resolution, etc. Learn more [here](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia#Syntax). - -* `get/updateScanSettings`: Configures the behavior of the scanner which includes `duplicateForgetTime`, `intervalTime` and `filter`, etc. - -* `get/updateRuntimeSettings`: Configures the decode engine. Find a full list of these settings and their corresponding descriptions [here](https://www.dynamsoft.com/barcode-reader/programming/javascript/api-reference/global-interfaces.html?utm_source=guide#runtimesettings). For example, the following uses the built-in "speed" settings with updated `localizationModes`. - - ``` javascript - await barcodeScanner.updateRuntimeSettings("speed"); - //await barcodeScanner.updateRuntimeSettings("balance"); //alternative - //await barcodeScanner.updateRuntimeSettings("coverage"); //alternative - let settings = await barcodeScanner.getRuntimeSettings(); - settings.localizationModes = [ - Dynamsoft.DBR.EnumLocalizationMode.LM_CONNECTED_BLOCKS, - Dynamsoft.DBR.EnumLocalizationMode.LM_SCAN_DIRECTLY, - Dynamsoft.DBR.EnumLocalizationMode.LM_LINES, 0, 0, 0, 0, 0 - ]; - await barcodeScanner.updateRuntimeSettings(settings); - ``` - - Try in [JSFiddle](https://jsfiddle.net/DynamsoftTeam/f24h8c1m/). - - See also [settings samples](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/parameter-settings.html?ver=latest&utm_source=guide). - -#### Customize the UI - -The built-in UI of the `BarcodeScanner` object is defined in the file `dist/dbr.scanner.html` . There are a few ways to customize it: - -* Modify the file `dist/dbr.scanner.html` directly. - - This option is only possible when you host this file on your own web server instead of using a CDN. - -* Copy the file `dist/dbr.scanner.html` to your application, modify it and use the the API `defaultUIElementURL` to set it as the default UI. - - ``` javascript - Dynamsoft.DBR.BarcodeScanner.defaultUIElementURL = "THE-URL-TO-THE-FILE"; - ``` - - > You must set `defaultUIElementURL` before you call `createInstance()` . - -* Append the default UI element to your page, customize it before showing it. - - ``` html -
- ``` - - ``` javascript - document.getElementById('scannerUI').appendChild(scanner.getUIElement()); - document.getElementsByClassName('dbrScanner-btn-close')[0].hidden = true; // Hide the close button - ``` - -* Build the UI element into your own web page and specify it with the API `setUIElement(HTMLElement)`. - - - Embed the video - - ``` html -
- -
- - ``` - - > The video element must have the class `dbrScanner-video` . - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/2jzeq1r6/) - - - Add the camera list and resolution list - - If the class names for these lists match the default ones, `dbrScanner-sel-camera` and `dbrScanner-sel-resolution` , the library will automatically populate the lists and handle the camera/resolution switching. - - ``` html - - ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/nbj75vxu/) - - ``` html - - ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/25v08paf/) - - > By default, 8 hard-coded resolutions are populated as options. You can show only a custom set of options by hardcoding them. - - ``` html - - ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/tnfjks4q/) - - > Generally, you need to provide a resolution that the camera supports. However, in case a camera does not support the specified resolution, it usually uses the nearest supported resolution. As a result, the selected resolution may not be the actual resolution used. In this case, add an option with the class name `dbrScanner-opt-gotResolution` (as shown above) and the library will then use it to show the actual resolution. - -See also [UI customization samples](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/ui-customization.html?ver=latest&utm_source=guide). - -Interested to test it further? Read on to learn how to request a 30-day free trial. - -## Requesting a Trial - -You can request a 30-day free trial license via the Request a Trial License link. Or you can [contact our support team](https://www.dynamsoft.com/contact/?utm_source=github) to get a free trial license. - -Since v8.2.5, a free public trial license is used by default if no license is specified. - -## System Requirements - -This library requires the following features which are supported by all modern mainstream browsers: - -* `WebAssembly`, `Blob`, `URL`/`createObjectURL`, `Web Workers`, `import` - - The above four features are required for the library to work. - -* `MediaDevices`/`getUserMedia` - - This API is only required for in-browser video streaming. If a browser does not support this API, the [Single Frame Mode](https://www.dynamsoft.com/barcode-reader/programming/javascript/api-reference/BarcodeScanner.html?ver=latest&utm_source=guide#singleframemode) will be used automatically. If the API exists but doesn't work correctly, the Single Frame Mode can be used as an alternative way to access the camera. - -The following table is a list of supported browsers based on the above requirements: - - Browser Name | Version - :-: | :-: - Chrome | v57+ (v59+ on Android/iOS1) - Firefox | v52+ (v55+ on Android/iOS1) - Edge2 | v16+ - Safari3 | v11+ - - 1 iOS 14.3+ is required for camera video streaming in Chrome and Firefox or Apps using webviews. - - 2 On Edge, due to strict Same-origin policy, you must host the library files on the same domain as your web page. - - 3 Safari 11.2.2 ~ 11.2.6 are not supported. - -Apart from the browsers, the operating systems may impose some limitations of their own that could restrict the use of the library. Browser compatibility ultimately depends on whether the browser on that particular operating system supports the features listed above. - -## Hosting the library - -### Step One: Deploy the dist folder - -Once you have downloaded the library, you can locate the "dist" directory and copy it to your server (usually as part of your website / web application). The following shows some of the files in this directory: - -* `dbr.js` // The main library file -* `dbr.mjs` // For using the library as a module (` -``` - -Optionally, you may also need to [specify the location of the "engine" files](#specify-the-location-of-the-engine-files). - -## Advanced Usage - -In addition to the content mentioned above, the library has many other settings and options that you can adjust to best suit your usage. To read more, please see [advanced usage](https://www.dynamsoft.com/barcode-reader/programming/javascript/user-guide/advanced-usage.html?ver=latest&utm_source=guide). - -## How to Upgrade - -If you are using an older version of the library and want to upgrade it to the latest version, please read more on [how to upgrade](https://www.dynamsoft.com/barcode-reader/programming/javascript/upgrade-guide/?ver=latest&utm_source=guide). - -## FAQ - -### Can I open the web page directly from the hard drive? - -Yes, for simple testing purposes, it's perfectly fine to open the file directly from the hard drive. However, you might encounter some issues in doing so (like unable to access the camera, etc.). The recommendation is to deploy this page to your web server and run it over **HTTPS**. If you don't have a ready-to-use web server but have a package manager like *npm* or *yarn*, you can set up a simple HTTP server in minutes. Check out [http-server on npm](https://www.npmjs.com/package/http-server) or [yarn](https://yarnpkg.com/package/http-server). - -### Why can't I use my camera? - -If you open the web page as `file:///` or `http://`, the camera may not work and you see the following error in 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 equivalent error is: - -> Trying to call getUserMedia from an insecure document. - -You get this error because the API [getUserMedia](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia) requires HTTPS to access the camera. - -* If you use Chrome or Firefox, you might not get the error because these two browsers allow camera access via file:/// and http://localhost. - -To make sure your web application can access the camera, please configure your web server to support HTTPS. The following links may help. - - - NGINX: [Configuring HTTPS servers](https://nginx.org/en/docs/http/configuring_https_servers.html) - - IIS: [Create a Self Signed Certificate in IIS](https://aboutssl.org/how-to-create-a-self-signed-certificate-in-iis/) - - Tomcat: [Setting Up SSL on Tomcat in 5 minutes](https://dzone.com/articles/setting-ssl-tomcat-5-minutes) - - Node.js: [npm tls](https://nodejs.org/docs/v0.4.1/api/tls.html) - -### Accounting for newline characters in the barcode result -When it comes to HTML, newline characters (`\n`) are not interpreted as they normally would. Therefore, if a barcode result contains a newline character, and you display the result in an alert box or some other text element, then the newline character will most probably be ignored. - -There are two ways in which you can resolve this: -1. Wrap the element used to display the result in a `
` element.
-2. Manually replace each `\n` character in the result with `
` diff --git a/programming-old/javascript/user-guide/index-v8.8.5.md b/programming-old/javascript/user-guide/index-v8.8.5.md deleted file mode 100644 index 74db661c..00000000 --- a/programming-old/javascript/user-guide/index-v8.8.5.md +++ /dev/null @@ -1,527 +0,0 @@ ---- -layout: default-layout -title: v8.8.5 User Guide - Dynamsoft Barcode Reader JavaScript Edition -description: This is the user guide of Dynamsoft Barcode Reader JavaScript SDK. -keywords: user guide, javascript, js -breadcrumbText: User Guide -noTitleIndex: true -needGenerateH3Content: true -needAutoGenerateSidebar: true -permalink: /programming/javascript/user-guide/index-v8.8.5.html ---- - -# Dynamsoft Barcode Reader for Your Website - -Turn your web page into a barcode scanner with just a few lines of code. - -![version](https://img.shields.io/npm/v/dynamsoft-javascript-barcode.svg) -![downloads](https://img.shields.io/npm/dm/dynamsoft-javascript-barcode.svg) -![jsdelivr](https://img.shields.io/jsdelivr/npm/hm/dynamsoft-javascript-barcode.svg) -![](https://img.shields.io/snyk/vulnerabilities/npm/dynamsoft-javascript-barcode.svg) - -[![](https://img.shields.io/badge/Download-Offline%20SDK-orange)](https://www.dynamsoft.com/barcode-reader/downloads/?utm_source=guide&product=dbr&package=js) - -Once integrated, your users can open your website in a browser, access their cameras and read barcodes directly from the video input. - -In this guide, you will learn step by step on how to integrate this library into your website. - -[TEST THE LIBRARY](https://www.dynamsoft.com/barcode-reader/downloads/?utm_source=guide&product=dbr&package=js) - -> For back-end barcode reading with Node.js, see [Dynamsoft Barcode Reader for Node](https://github.com/Dynamsoft/javascript-barcode/blob/main/README.NODE.md). - -**Table of Contents** - -* [Hello World - Simplest Implementation](#hello-world---simplest-implementation) -* [Building your own page](#building-your-own-page) - - [Include the library](#include-the-library) - - [Configure the library](#configure-the-library) - - [Interact with the library](#interact-with-the-library) -* [Requesting A Trial](#requesting-a-trial) -* [System Requirements](#system-requirements) -* [Hosting the Library](#hosting-the-library) -* [Advanced Usage](#advanced-usage) -* [How to Upgrade](#how-to-upgrade) -* [FAQ](#faq) - -**Popular Examples** - -* [Basic Implementation](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/helloworld-mincode.html?ver=latest&utm_source=guide) -* [Use the library in Angular](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/helloworld-angular.html?ver=latest&utm_source=guide) -* [Use the library in React](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/helloworld-reactjs.html?ver=latest&utm_source=guide) -* [Use the library in Vue](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/helloworld-vuejs.html?ver=latest&utm_source=guide) -* [Use the library in a PWA APP](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/helloworld-pwa.html?ver=latest&utm_source=guide) - -You can also: - -* [Try All Online Examples](https://demo.dynamsoft.com/Samples/DBR/JS/index.html?utm_source=guide) -* [Try the Official Demo](https://demo.dynamsoft.com/barcode-reader-js/?utm_source=guide) - -## Hello World - Simplest Implementation - -Let's start by testing the "Hello World" example of the library which demonstrates how to use the minimum code to enable a web page to read barcodes from a live video stream. - -* Basic Requirements - + Internet connection - + [A supported browser](#system-requirements) - + Camera access - -### Step One: Check the code of the example - -The complete code of the "Hello World" example is shown below - -``` html - - - - - - - - - -``` - -> You can also find the code (with more comments) [on GitHub](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/master/1.hello-world/1.minimum-code.html?utm_source=guide). - -*About the code* - - + `createInstance()`: This method creates a `BarcodeScanner` object. This object can read barcodes directly from a video input with the help of its interactive UI (hidden by default) and the [MediaDevices interface](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices). - - + `onFrameRead`: This event is triggered every time the library finishes scanning a video frame. The `results` object contains all the barcode results that the library have found on this frame. In this example, we print the results to the browser console. - - + `onUnduplicatedRead`: This event is triggered when the library finds a new barcode, which is not a duplicate among multiple frames. `txt` holds the barcode text value while `result` is an object that holds details of the barcode. In this example, an alert will be displayed for this new barcode. - - + `show()`: This method brings up the built-in UI of the `BarcodeScanner` object and starts scanning. - -### Step Two: Test the example - -You can choose one of three ways to test the example: - -* [Hello World example - online](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/1.minimum-code.html?utm_source=guide) -* [Hello World example via JSFiddle](https://jsfiddle.net/DynamsoftTeam/pL4e7yrd/) -* [Download a copy](https://tst.dynamsoft.com/public/download/dbr/browser/code/helloworld.zip) of the example code and set it up locally - -Either way, you open the example page in a browser, allow the page to access your camera and the video will show up on the page. After that, you can point the camera at something with a barcode to read it. - -If the barcode is decoded, an alert will pop up with the result text. At the same time, the barcode location will be highlighted in the video feed. - - > For first use, you may need to wait a few seconds for the library to initialize. - -*Note*: - - + The library only scans a new frame when it has finished scanning the previous frame. The interval between two consecutive frames might not be enough time for the library to process the 1st frame (for 30 FPS, the interval is about 33 ms), therefore, not all frames are scanned. - - + The library requires a license to work. However, when no license is specified in the code, a [free public trial license](https://www.dynamsoft.com/license-server/docs/about/terms.html?ver=latest#public-trial-license?utm_source=guide) will automatically be used during which you can make initial evaluation of the library to decide whether or not you want to evaluate it further. If you do, you can [request a private trial license](#requesting-a-trial). - - > Network connection is required for the free public trial license to work. - -If the test doesn't go as expected, you can check out the [FAQ](#faq) or [contact us](https://www.dynamsoft.com/contact/?utm_source=guide). - -## Building your own page - -### Include the library - -#### Use a CDN - -The simplest way to include the library is to use either the [jsDelivr](https://jsdelivr.com/) or [UNPKG](https://unpkg.com/) CDN. The "hello world" example above uses **jsDelivr**. - -* jsDelivr - - ``` html - - ``` - -* UNPKG - - ``` html - - ``` - -#### Host the library yourself - -Besides using the CDN, you can also download the library and host its files on your own website / server before including it in your application. - -The following shows a few ways to download the library. - -* From the website - - [Download the JavaScript Package](https://www.dynamsoft.com/barcode-reader/downloads/?utm_source=guide) - -* yarn - - ```cmd - $ yarn add dynamsoft-javascript-barcode - ``` - -* npm - - ``` - $ npm install dynamsoft-javascript-barcode --save - ``` - -Depending on how you downloaded the library and where you put it. You can typically include it like this: - -``` html - -``` - -or - -``` html - -``` - -Read more on [how to host the library](#hosting-the-library). - -### Configure the library - -Before using the library, you need to configure a few things. - -#### Specify the license - -The library requires a license to work, use the APIs `organizationID` and / or `handshakeCode` to specify how to acquire the license. - -``` javascript -Dynamsoft.DBR.BarcodeScanner.organizationID = "YOUR-ORGANIZATION-ID"; // Required. -Dynamsoft.DBR.BarcodeScanner.handshakeCode = "A-SPECIFIC-HANDSHAKECODE"; // Optional, if not specified, the default handshake code is used. -Dynamsoft.DBR.BarcodeScanner.sessionPassword = "PASSWORD-TO-PROTECT-YOUR-LICENSE"; // Optional but recomended, use it to protect your license. -Dynamsoft.DBR.BarcodeScanner.licenseServer = ["YOUR-OWN-MAIN-DLS", "YOUR-OWN-STANDBY-DLS"]; //Optional, ignore this line if you are using Dynamsoft-hosting DLS. -``` - -*Note*: - -+ Network connection is required for the license to work. -+ If nothing is specified like the above "hello world" example, a [free public trial license](https://www.dynamsoft.com/license-server/docs/about/terms.html?ver=latest#public-trial-license?utm_source=guide) will be automatically used. -+ The license is actually fetched during the creation of a `BarcodeScanner` or `BarcodeReader` instance. -+ If a public network connection is not available, you can choose to host a license server in your private network. [Contact us](https://www.dynamsoft.com/contact/?utm_source=guide) for more information. - -An alternative way to specify the license is to use an alphanumeric string which does not require a network connection. The following shows how it could be used. [Contact us](https://www.dynamsoft.com/contact/?utm_source=guide) for more information. - -```javascript -Dynamsoft.DBR.BarcodeReader.productKeys = "t0068NQAAACgTVU2aucyxqETXKkiomqhV7YoLrnqjLiQQRSH5DBV1UtIs4..." -``` - -Or - -```html - -``` - -#### Specify the location of the "engine" files - -The "engine" files refer to *.worker.js, *.wasm.js and *.wasm, etc. which are loaded by the main library at runtime. This configuration option uses the API `engineResourcePath` and is often not required as these files usually are in the same location with the main library file (dbr.js). However, in cases where the engine files are not in the same location as the main library file (for example, with frameworks like Angular or React, dbr.js is compiled into another file), this configuration will be required. - -The following code uses the jsDelivr CDN, feel free to change it to your own location of these files. - -``` javascript -Dynamsoft.DBR.BarcodeScanner.engineResourcePath = "https://cdn.jsdelivr.net/npm/dynamsoft-javascript-barcode@8.8.5/dist/"; -``` - -### Interact with the library - -#### Create a `BarcodeScanner` object - -You can use one of two classes ( `BarcodeScanner` and `BarcodeReader` ) to interact with the library. `BarcodeReader` is a low-level class that processes images directly. `BarcodeScanner` , on the other hand, inherits from `BarcodeReader` and provides high-level APIs and a built-in GUI to allow continuous barcode scanning on video frames. We'll focus on `BarcodeScanner` in this guide. - -To use the library, we first create a `BarcodeScanner` object. - -``` javascript -let scanner = null; -try { - scanner = await Dynamsoft.DBR.BarcodeScanner.createInstance(); -} catch (ex) { - console.error(ex); -} -``` - -When creating a `BarcodeScanner` object within a function which may be called more than once, it's best to use a "helper" variable to avoid double creation such as `pScanner` in the following code - -``` javascript -let scanner = null, pScanner = null; -function createBarcodeScanner(){ - try { - scanner = await (pScanner = pScanner || Dynamsoft.DBR.BarcodeScanner.createInstance()); - } catch (ex) { - console.error(ex); - } -} -``` - -*Note*: - -* The creation of an object consists of two parallel tasks: one is to download and compile the "engine", the other is to fetch a license from Dynamsoft License Server (assuming an online license is used). - -#### Configure the `BarcodeScanner` object - -Let's take a look at the following code snippets first: - -``` javascript -// set which camera and what resolution to use -var allCameras = await scanner.getAllCameras(); -await scanner.setCurrentCamera(allCameras[0].deviceId); -await scanner.setResolution(1280, 720); -``` - -``` javascript -// set up the scanner behavior -let scanSettings = await scanner.getScanSettings(); -// disregard duplicated results found in a specified time period (in milliseconds) -scanSettings.duplicateForgetTime = 5000; -// set a scan interval in milliseconds so the library may release the CPU from time to time -scanSettings.intervalTime = 300; -await scanner.updateScanSettings(scanSettings); -``` - -``` javascript -// use one of the built-in RuntimeSetting templates: "single" (decode a single barcode, the default mode), "speed", "balance" and "coverage" -await scanner.updateRuntimeSettings("speed"); - -// make changes to the template. The code below demonstrates how to specify enabled symbologies -let runtimeSettings = await scanner.getRuntimeSettings(); -runtimeSettings.barcodeFormatIds = Dynamsoft.DBR.EnumBarcodeFormat.BF_ONED | Dynamsoft.DBR.EnumBarcodeFormat.BF_QR_CODE; -await scanner.updateRuntimeSettings(runtimeSettings); -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/yfkcajxz/) - -As you can see from the above code snippets, there are three types of configurations: - -* `get/updateVideoSettings`: Configures the data source, i.e., the camera. These settings include which camera to use, the resolution, etc. Learn more [here](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia#Syntax). - -* `get/updateScanSettings`: Configures the behavior of the scanner which includes `duplicateForgetTime`, `intervalTime` and `filter`, etc. - -* `get/updateRuntimeSettings`: Configures the decode engine. Find a full list of these settings and their corresponding descriptions [here](https://www.dynamsoft.com/barcode-reader/programming/javascript/api-reference/global-interfaces.html?utm_source=guide#runtimesettings). For example, the following uses the built-in "speed" settings with updated `localizationModes`. - - ``` javascript - await barcodeScanner.updateRuntimeSettings("speed"); - //await barcodeScanner.updateRuntimeSettings("balance"); //alternative - //await barcodeScanner.updateRuntimeSettings("coverage"); //alternative - let settings = await barcodeScanner.getRuntimeSettings(); - settings.localizationModes = [ - Dynamsoft.DBR.EnumLocalizationMode.LM_CONNECTED_BLOCKS, - Dynamsoft.DBR.EnumLocalizationMode.LM_SCAN_DIRECTLY, - Dynamsoft.DBR.EnumLocalizationMode.LM_LINES, 0, 0, 0, 0, 0 - ]; - await barcodeScanner.updateRuntimeSettings(settings); - ``` - - Try in [JSFiddle](https://jsfiddle.net/DynamsoftTeam/f24h8c1m/). - - See also [settings samples](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/parameter-settings.html?ver=latest&utm_source=guide). - -#### Customize the UI - -The built-in UI of the `BarcodeScanner` object is defined in the file `dist/dbr.scanner.html` . There are a few ways to customize it: - -* Modify the file `dist/dbr.scanner.html` directly. - - This option is only possible when you host this file on your own web server instead of using a CDN. - -* Copy the file `dist/dbr.scanner.html` to your application, modify it and use the the API `defaultUIElementURL` to set it as the default UI. - - ``` javascript - Dynamsoft.DBR.BarcodeScanner.defaultUIElementURL = "THE-URL-TO-THE-FILE"; - ``` - - > You must set `defaultUIElementURL` before you call `createInstance()` . - -* Append the default UI element to your page, customize it before showing it. - - ``` html -
- ``` - - ``` javascript - document.getElementById('scannerUI').appendChild(scanner.getUIElement()); - document.getElementsByClassName('dbrScanner-btn-close')[0].hidden = true; // Hide the close button - ``` - -* Build the UI element into your own web page and specify it with the API `setUIElement(HTMLElement)`. - - - Embed the video - - ``` html -
- -
- - ``` - - > The video element must have the class `dbrScanner-video` . - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/2jzeq1r6/) - - - Add the camera list and resolution list - - If the class names for these lists match the default ones, `dbrScanner-sel-camera` and `dbrScanner-sel-resolution` , the library will automatically populate the lists and handle the camera/resolution switching. - - ``` html - - ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/nbj75vxu/) - - ``` html - - ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/25v08paf/) - - > By default, 8 hard-coded resolutions are populated as options. You can show only a custom set of options by hardcoding them. - - ``` html - - ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/tnfjks4q/) - - > Generally, you need to provide a resolution that the camera supports. However, in case a camera does not support the specified resolution, it usually uses the nearest supported resolution. As a result, the selected resolution may not be the actual resolution used. In this case, add an option with the class name `dbrScanner-opt-gotResolution` (as shown above) and the library will then use it to show the actual resolution. - -See also [UI customization samples](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/ui-customization.html?ver=latest&utm_source=guide). - -Interested to test it further? Read on to learn how to request a 30-day free trial. - -## Requesting a Trial - -You can request a 30-day free trial license via the Request a Trial License link. Or you can [contact our support team](https://www.dynamsoft.com/contact/?utm_source=github) to get a free trial license. - -Since v8.2.5, a free public trial license is used by default if no license is specified. - -## System Requirements - -This library requires the following features which are supported by all modern mainstream browsers: - -* `WebAssembly`, `Blob`, `URL`/`createObjectURL`, `Web Workers`, `import` - - The above four features are required for the library to work. - -* `MediaDevices`/`getUserMedia` - - This API is only required for in-browser video streaming. If a browser does not support this API, the [Single Frame Mode](https://www.dynamsoft.com/barcode-reader/programming/javascript/api-reference/BarcodeScanner.html?ver=latest&utm_source=guide#singleframemode) will be used automatically. If the API exists but doesn't work correctly, the Single Frame Mode can be used as an alternative way to access the camera. - -The following table is a list of supported browsers based on the above requirements: - - Browser Name | Version - :-: | :-: - Chrome | v57+ (v59+ on Android/iOS1) - Firefox | v52+ (v55+ on Android/iOS1) - Edge2 | v16+ - Safari3 | v11+ - - 1 iOS 14.3+ is required for camera video streaming in Chrome and Firefox or Apps using webviews. - - 2 On Edge, due to strict Same-origin policy, you must host the library files on the same domain as your web page. - - 3 Safari 11.2.2 ~ 11.2.6 are not supported. - -Apart from the browsers, the operating systems may impose some limitations of their own that could restrict the use of the library. Browser compatibility ultimately depends on whether the browser on that particular operating system supports the features listed above. - -## Hosting the library - -### Step One: Deploy the dist folder - -Once you have downloaded the library, you can locate the "dist" directory and copy it to your server (usually as part of your website / web application). The following shows some of the files in this directory: - -* `dbr.js` // The main library file -* `dbr.mjs` // For using the library as a module (` -``` - -Optionally, you may also need to [specify the location of the "engine" files](#specify-the-location-of-the-engine-files). - -## Advanced Usage - -In addition to the content mentioned above, the library has many other settings and options that you can adjust to best suit your usage. To read more, please see [advanced usage](https://www.dynamsoft.com/barcode-reader/programming/javascript/user-guide/advanced-usage.html?ver=latest&utm_source=guide). - -## How to Upgrade - -If you are using an older version of the library and want to upgrade it to the latest version, please read more on [how to upgrade](https://www.dynamsoft.com/barcode-reader/programming/javascript/upgrade-guide/?ver=latest&utm_source=guide). - -## FAQ - -### Can I open the web page directly from the hard drive? - -Yes, for simple testing purposes, it's perfectly fine to open the file directly from the hard drive. However, you might encounter some issues in doing so (like unable to access the camera, etc.). The recommendation is to deploy this page to your web server and run it over **HTTPS**. If you don't have a ready-to-use web server but have a package manager like *npm* or *yarn*, you can set up a simple HTTP server in minutes. Check out [http-server on npm](https://www.npmjs.com/package/http-server) or [yarn](https://yarnpkg.com/package/http-server). - -### Why can't I use my camera? - -If you open the web page as `file:///` or `http://`, the camera may not work and you see the following error in 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 equivalent error is: - -> Trying to call getUserMedia from an insecure document. - -You get this error because the API [getUserMedia](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia) requires HTTPS to access the camera. - -* If you use Chrome or Firefox, you might not get the error because these two browsers allow camera access via file:/// and http://localhost. - -To make sure your web application can access the camera, please configure your web server to support HTTPS. The following links may help. - - - NGINX: [Configuring HTTPS servers](https://nginx.org/en/docs/http/configuring_https_servers.html) - - IIS: [Create a Self Signed Certificate in IIS](https://aboutssl.org/how-to-create-a-self-signed-certificate-in-iis/) - - Tomcat: [Setting Up SSL on Tomcat in 5 minutes](https://dzone.com/articles/setting-ssl-tomcat-5-minutes) - - Node.js: [npm tls](https://nodejs.org/docs/v0.4.1/api/tls.html) - -### Accounting for newline characters in the barcode result -When it comes to HTML, newline characters (`\n`) are not interpreted as they normally would. Therefore, if a barcode result contains a newline character, and you display the result in an alert box or some other text element, then the newline character will most probably be ignored. - -There are two ways in which you can resolve this: -1. Wrap the element used to display the result in a `
` element.
-2. Manually replace each `\n` character in the result with `
` diff --git a/programming-old/javascript/user-guide/index-v8.8.7.md b/programming-old/javascript/user-guide/index-v8.8.7.md deleted file mode 100644 index 27b3c833..00000000 --- a/programming-old/javascript/user-guide/index-v8.8.7.md +++ /dev/null @@ -1,554 +0,0 @@ ---- -layout: default-layout -title: v8.8.7 User Guide - Dynamsoft Barcode Reader JavaScript Edition -description: This is the user guide of Dynamsoft Barcode Reader JavaScript SDK. -keywords: user guide, javascript, js -breadcrumbText: User Guide -noTitleIndex: true -needGenerateH3Content: true -needAutoGenerateSidebar: true -permalink: /programming/javascript/user-guide/index-v8.8.7.html ---- - - - -# Dynamsoft Barcode Reader for Your Website - -Turn your web page into a barcode scanner with just a few lines of code. - -![version](https://img.shields.io/npm/v/dynamsoft-javascript-barcode.svg) -![downloads](https://img.shields.io/npm/dm/dynamsoft-javascript-barcode.svg) -![jsdelivr](https://img.shields.io/jsdelivr/npm/hm/dynamsoft-javascript-barcode.svg) -![](https://img.shields.io/snyk/vulnerabilities/npm/dynamsoft-javascript-barcode.svg) - -[![](https://img.shields.io/badge/Download-Offline%20SDK-orange)](https://www.dynamsoft.com/barcode-reader/downloads/?utm_source=guide&product=dbr&package=js) - -Once integrated, your users can open your website in a browser, access their cameras and read barcodes directly from the video input. - -In this guide, you will learn step by step on how to integrate this library into your website. - -[GET THE LIBRARY](https://www.dynamsoft.com/barcode-reader/downloads/?utm_source=guide&product=dbr&package=js) - -> For back-end barcode reading with Node.js, see [Dynamsoft Barcode Reader for Node](https://www.npmjs.com/package/dynamsoft-node-barcode). - -**Table of Contents** - -* [Hello World - Simplest Implementation](#hello-world---simplest-implementation) -* [Building your own page](#building-your-own-page) - + [Include the library](#include-the-library) - + [Configure the library](#configure-the-library) - + [Interact with the library](#interact-with-the-library) -* [Requesting A Trial](#requesting-a-trial) -* [System Requirements](#system-requirements) -* [Hosting the Library (optional)](#hosting-the-library-optional) -* [Advanced Usage](#advanced-usage) -* [How to Upgrade](#how-to-upgrade) -* [FAQ](#faq) - -**Popular Examples** - -* Basic Implementation - [Guide](#hello-world---simplest-implementation) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/master/1.hello-world/1.minimum-code.html) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/1.minimum-code.html?utm_source=guide) -* Angular App - [Guide](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/helloworld-angular.html?ver=8.8.7&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/master/1.hello-world/3.read-video-angular) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/3.read-video-angular/dist/hello-world/?utm_source=guide) -* React App - [Guide](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/helloworld-reactjs.html?ver=8.8.7&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/master/1.hello-world/4.read-video-react) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/4.read-video-react/build/?utm_source=guide) -* Vue App - [Guide](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/helloworld-vuejsv3.html?ver=8.8.7&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/master/1.hello-world/6.read-video-vue3) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/6.read-video-vue3/dist/?utm_source=guide) -* PWA App - [Guide](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/helloworld-pwa.html?ver=8.8.7&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/master/1.hello-world/10.read-video-pwa) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/10.read-video-pwa/helloworld-pwa.html?utm_source=guide) - -You can also: - -* Try the Official Demo - [Run](https://demo.dynamsoft.com/barcode-reader-js/?utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-demo) -* Try Online Examples - [Run](https://demo.dynamsoft.com/Samples/DBR/JS/index.html?utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples) - -
- -## Hello World - Simplest Implementation - -Let's start with the "Hello World" example of the library which demonstrates how to use the minimum code to enable a web page to read barcodes from a live video stream. - -* Basic Requirements - + Internet connection - + [A supported browser](#system-requirements) - + Camera access - -### Step One: Check the code of the example - -The complete code of the "Hello World" example is shown below - -```html - - - - - - - - - -``` - -

- - Code in Github - -   - - Run via JSFiddle - -   - - Run in Dynamsoft - -   - - Download from Dynamsoft - -

- ------ - -*About the code* - - + `createInstance()`: This method creates a `BarcodeScanner` object. This object can read barcodes directly from a video input with the help of its interactive UI (hidden by default) and the MediaDevices interface. - - + `onFrameRead`: This event is triggered every time the library finishes scanning a video frame. The `results` object contains all the barcode results that the library have found on this frame. In this example, we print the results to the browser console. - - + `onUnduplicatedRead`: This event is triggered when the library finds a new barcode, which is not a duplicate among multiple frames. `txt` holds the barcode text value while `result` is an object that holds details of the barcode. In this example, an alert will be displayed for this new barcode. - - + `show()`: This method brings up the built-in UI of the `BarcodeScanner` object and starts scanning. - -### Step Two: Test the example - -Open the example page in a browser, allow the page to access your camera and the video will show up on the page. After that, you can point the camera at a barcode to read it. - -When a barcode is decoded, you will see the result text pop up and the barcode location will be highlighted in the video feed. - - > For first use, you may need to wait a few seconds for the library to initialize. - -*Note*: - - + The library requires a license to work. However, when no license is specified in the code, a [free 1-day public trial license](https://www.dynamsoft.com/license-server/docs/about/terms.html?ver=latest#public-trial-license?utm_source=guide) will automatically be used during which you can make initial evaluation of the library to decide whether or not you want to evaluate it further. If you do, you can [request a 30-day private trial license](#requesting-a-trial). - > Network connection is required for the free public trial license to work. - -If the test doesn't go as expected, you can check out the [FAQ](#faq) or [contact us](https://www.dynamsoft.com/contact/?utm_source=guide). - -
- -## Building your own page - -### Include the library - -#### Use a CDN - -The simplest way to include the library is to use either the [jsDelivr](https://jsdelivr.com/) or [UNPKG](https://unpkg.com/) CDN. The "hello world" example above uses **jsDelivr**. - -* jsDelivr - - ```html - - ``` - -* UNPKG - - ```html - - ``` - -#### Host the library yourself - -Besides using the CDN, you can also download the library and host its files on your own website / server before including it in your application. - -A few ways to download the library: - -* From the website - - [Download the JavaScript Package](https://www.dynamsoft.com/barcode-reader/downloads/?utm_source=guide) - -* yarn - - ```cmd - $ yarn add dynamsoft-javascript-barcode - ``` - -* npm - - ``` - $ npm install dynamsoft-javascript-barcode --save - ``` - -Depending on how you downloaded the library and where you put it, you can typically include it like this: - -```html - -``` - -or - -```html - -``` - -Read more on [how to host the library](#hosting-the-library-optional). - -### Configure the library - -Before using the library, you need to configure a few things. - -#### Specify the license - -The library requires a license to work, use the API `license` to specify it. - -```javascript -Dynamsoft.DBR.BarcodeReader.license = - "YOUR-ORGANIZATION-ID or YOUR-HANDSHAKECODE or AN-OFFLINE-LICENSE or ANY-OTHER-TYPE-OF-SUPPORTED-LICENSE-STRING"; -``` - -Or - -```html - -``` - -*Note*: - -* When specified by YOUR-ORGANIZATION-ID or YOUR-HANDSHAKECODE, the license is an online license and a network connection to Dynamsoft License Server is required for it to work. -* In most cases, online licenses are offered. If you want to use an offline license, you can [contact us](https://www.dynamsoft.com/contact/?utm_source=guide). -* If nothing is specified like the above "hello world" example, a [free 1-day public trial license](https://www.dynamsoft.com/license-server/docs/about/terms.html?ver=latest#public-trial-license?utm_source=guide) will be automatically used. This license requires a network connection. - - -#### Specify the location of the "engine" files - -If the engine files (*.worker.js, *.wasm.js and *.wasm, etc.) are not in the same location with the main library file (dbr.js), you can use the API `engineResourcePath` to specify the engine path, for example: - -```javascript -//The following code uses the jsDelivr CDN, feel free to change it to your own location of these files -Dynamsoft.DBR.BarcodeScanner.engineResourcePath = "https://cdn.jsdelivr.net/npm/dynamsoft-javascript-barcode@8.8.7/dist/"; -``` - -This configuration is usually required with frameworks like Angular or React where dbr.js is compiled into another file. - -### Interact with the library - -#### Create a `BarcodeScanner` object - -You can use one of two classes ( `BarcodeScanner` and `BarcodeReader` ) to interact with the library. `BarcodeReader` is a low-level class that processes images directly. `BarcodeScanner`, on the other hand, inherits from `BarcodeReader` and provides high-level APIs and a built-in GUI to allow continuous barcode scanning on video frames. We'll focus on `BarcodeScanner` in this guide. - -To use the library, we first create a `BarcodeScanner` object. - -```javascript -let scanner = null; -try { - scanner = await Dynamsoft.DBR.BarcodeScanner.createInstance(); -} catch (ex) { - console.error(ex); -} -``` - -Tip: When creating a `BarcodeScanner` object within a function which may be called more than once, it's best to use a "helper" variable to avoid double creation such as `pScanner` in the following code - -```javascript -let pScanner = null; -document.getElementById('btn-scan').addEventListener('click', async () => { - try { - const scanner = await (pScanner = pScanner || Dynamsoft.DBR.BarcodeScanner.createInstance()); - } catch (ex) { - console.error(ex); - } -}); -``` - -#### Configure the `BarcodeScanner` object - -Let's take a look at the following code snippets first: - -```javascript -// set which camera and what resolution to use -let allCameras = await scanner.getAllCameras(); -await scanner.setCurrentCamera(allCameras[0].deviceId); -await scanner.setResolution(1280, 720); -``` - -```javascript -// set up the scanner behavior -let scanSettings = await scanner.getScanSettings(); -// disregard duplicated results found in a specified time period (in milliseconds) -scanSettings.duplicateForgetTime = 5000; -// set a scan interval in milliseconds so the library may release the CPU from time to time -scanSettings.intervalTime = 100; -await scanner.updateScanSettings(scanSettings); -``` - -```javascript -// use one of the built-in RuntimeSetting templates: "single" (decode a single barcode, the default mode), "speed", "balance" and "coverage" -await scanner.updateRuntimeSettings("speed"); - -// make changes to the template. The code below demonstrates how to specify enabled symbologies -let runtimeSettings = await scanner.getRuntimeSettings(); -runtimeSettings.barcodeFormatIds = Dynamsoft.DBR.EnumBarcodeFormat.BF_ONED | Dynamsoft.DBR.EnumBarcodeFormat.BF_QR_CODE; -await scanner.updateRuntimeSettings(runtimeSettings); -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/yfkcajxz/) - -As you can see from the above code snippets, there are three types of configurations: - -* `get/updateVideoSettings`: Configures the data source, i.e., the camera. These settings include which camera to use, the resolution, etc. Learn more here. - -* `get/updateScanSettings`: Configures the behavior of the scanner which includes `duplicateForgetTime`, `intervalTime` and `filter`, etc. - -* `get/updateRuntimeSettings`: Configures the decode engine with either a built-in template or a comprehensive `RuntimeSettings` object. For example, the following uses the built-in "speed" settings with updated `localizationModes`. - -> Find the full list of these settings here. - - ```javascript - await barcodeScanner.updateRuntimeSettings("speed"); - //await barcodeScanner.updateRuntimeSettings("balance"); //alternative - //await barcodeScanner.updateRuntimeSettings("coverage"); //alternative - let settings = await barcodeScanner.getRuntimeSettings(); - settings.localizationModes = [ - Dynamsoft.DBR.EnumLocalizationMode.LM_CONNECTED_BLOCKS, - Dynamsoft.DBR.EnumLocalizationMode.LM_SCAN_DIRECTLY, - Dynamsoft.DBR.EnumLocalizationMode.LM_LINES, 0, 0, 0, 0, 0 - ]; - await barcodeScanner.updateRuntimeSettings(settings); - ``` - - Try in [JSFiddle](https://jsfiddle.net/DynamsoftTeam/f24h8c1m/). - - See also [settings samples](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/parameter-settings.html?ver=8.8.7&utm_source=guide). - -#### Customize the UI - -The built-in UI of the `BarcodeScanner` object is defined in the file `dist/dbr.scanner.html` . There are a few ways to customize it: - -* Modify the file `dist/dbr.scanner.html` directly. - - This option is only possible when you host this file on your own web server instead of using a CDN. - -* Copy the file `dist/dbr.scanner.html` to your application, modify it and use the the API `defaultUIElementURL` to set it as the default UI. - - ```javascript - Dynamsoft.DBR.BarcodeScanner.defaultUIElementURL = "THE-URL-TO-THE-FILE"; - ``` - - - > You must set `defaultUIElementURL` before you call `createInstance()` . - -* Append the default UI element to your page, customize it before showing it. - - ```html -
- ``` - - ```javascript - document.getElementById('div-video-container').appendChild(scanner.getUIElement()); - document.getElementsByClassName('dce-btn-close')[0].hidden = true; // Hide the close button - ``` - -* Build the UI element into your own web page and specify it with the API `setUIElement(HTMLElement)`. - - + Embed the video - - ```html -
- -
- - ``` - - > The video element must have the class `dce-video` . - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/2jzeq1r6/) - - + Add the camera list and resolution list - - - If the class names for these lists match the default ones, `dce-sel-camera` and `dce-sel-resolution` , the library will automatically populate the lists and handle the camera/resolution switching. - - ```html - - ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/nbj75vxu/) - - ```html - - ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/25v08paf/) - - > By default, 8 hard-coded resolutions are populated as options. You can show only a custom set of options by hardcoding them. - - ```html - - ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/tnfjks4q/) - - > Generally, you need to provide a resolution that the camera supports. However, in case a camera does not support the specified resolution, it usually uses the nearest supported resolution. As a result, the selected resolution may not be the actual resolution used. In this case, add an option with the class name `dce-opt-gotResolution` (as shown above) and the library will then use it to show the actual resolution. - -See also [UI customization samples](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/ui-customization.html?ver=8.8.7&utm_source=guide). - -
- -## Requesting a Trial - -You can request a 30-day free private trial license via the Request a Trial License link. Or you can [contact our support team](https://www.dynamsoft.com/contact/?utm_source=github) to get a free trial license. - -Since v8.2.5, a free public trial license is used by default if no license is specified. - -
- -## System Requirements - -This library requires the following features which are supported by all modern mainstream browsers: - -* `WebAssembly`, `Blob`, `URL`/`createObjectURL`, `Web Workers` - - - The above four features are required for the library to work. - -* `MediaDevices`/`getUserMedia` - - This API is only required for in-browser video streaming. If a browser does not support this API, the [Single Frame Mode](https://www.dynamsoft.com/barcode-reader/programming/javascript/api-reference/BarcodeScanner.html?ver=8.8.7&utm_source=guide#singleframemode) will be used automatically. If the API exists but doesn't work correctly, the Single Frame Mode can be used as an alternative way to access the camera. - -The following table is a list of supported browsers based on the above requirements: - - Browser Name | Version - :-: | :-: - Chrome | v57+ (v59+ on Android/iOS1) - Firefox | v52+ (v55+ on Android/iOS1) - Edge2 | v16+ - Safari3 | v11+ - - 1 iOS 14.3+ is required for camera video streaming in Chrome and Firefox or Apps using webviews. - - 2 On Edge, due to strict Same-origin policy, you must host the library files on the same domain as your web page. - - 3 Safari 11.2.2 ~ 11.2.6 are not supported. - -Apart from the browsers, the operating systems may impose some limitations of their own that could restrict the use of the library. Browser compatibility ultimately depends on whether the browser on that particular operating system supports the features listed above. - -
- -## Hosting the library (optional) - -### Step One: Deploy the dist folder - -Once you have downloaded the library, you can locate the "dist" directory and copy it to your server (usually as part of your website / web application). - -Some of the files in this directory: - -* `dbr.js` // The main library file -* `dbr.mjs` // For using the library as a module (` -``` - -Optionally, you may also need to [specify the location of the "engine" files](#specify-the-location-of-the-engine-files). - -
- -## Advanced Usage - -In addition to the above basic settings, the library has many more settings and options that you can adjust to best suit your usage. To read more, please see [advanced usage](https://www.dynamsoft.com/barcode-reader/programming/javascript/user-guide/advanced-usage.html?ver=8.8.7&utm_source=guide). - -
- -## How to Upgrade - -If you want to upgrade the library from an old version to a newer one, please see [how to upgrade](https://www.dynamsoft.com/barcode-reader/programming/javascript/upgrade-guide/?ver=8.8.7&utm_source=guide). - -
- -## FAQ - -### Can I open the web page directly from the hard drive? - -Yes, for simple testing purposes, it's perfectly fine to open the file directly from the hard drive. However, you might encounter some issues in doing so (like unable to access the camera, etc.). The recommendation is to deploy this page to your web server and run it over **HTTPS**. If you don't have a ready-to-use web server but have a package manager like *npm* or *yarn*, you can set up a simple HTTP server in minutes. Check out [http-server on npm](https://www.npmjs.com/package/http-server). - -### Why can't I use my camera? - -If you open the web page as `file:///` or `http://` , the camera may not work and you see the following error in 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 equivalent error is: - -> Trying to call getUserMedia from an insecure document. - -You get this error because the API getUserMedia requires HTTPS to access the camera. - -* If you use Chrome or Firefox, you might not get the error because these two browsers allow camera access via file:/// and http://localhost. - -To make sure your web application can access the camera, please configure your web server to support HTTPS. The following links may help. - - + NGINX: Configuring HTTPS servers - + IIS: Create a Self Signed Certificate in IIS - + Tomcat: Setting Up SSL on Tomcat in 5 minutes - + Node.js: npm tls - -### Accounting for newline characters in the barcode result - -When it comes to HTML, newline characters ( `\n` ) are not interpreted as they normally would. Therefore, if a barcode result contains a newline character, and you display the result in an modal dialogue box or some other text elements, then the newline character will probably be ignored. - -There are two ways in which you can resolve this: -1. Wrap the element used to display the result in a `
` element.
-2. Manually replace each `\n` character in the result with `
` diff --git a/programming-old/javascript/user-guide/index-v9.0.0.md b/programming-old/javascript/user-guide/index-v9.0.0.md deleted file mode 100644 index 4b0f9b07..00000000 --- a/programming-old/javascript/user-guide/index-v9.0.0.md +++ /dev/null @@ -1,478 +0,0 @@ ---- -layout: default-layout -title: v9.0.0 User Guide - Dynamsoft Barcode Reader JavaScript Edition -description: This is the user guide of Dynamsoft Barcode Reader JavaScript SDK. -keywords: user guide, javascript, js -breadcrumbText: User Guide -noTitleIndex: true -needGenerateH3Content: true -needAutoGenerateSidebar: true -permalink: /programming/javascript/user-guide/index-v9.0.0.html ---- - - - -# Barcode Reader for Your Website - -[Dynamsoft Barcode Reader JavaScript Edition](https://www.dynamsoft.com/barcode-reader/sdk-javascript/) is equipped with industry-leading algorithms for exceptional speed, accuracy and read rates in barcode reading. With its well-designed API, you can turn your web page into a barcode scanner with just a few lines of code. - -![version](https://img.shields.io/npm/v/dynamsoft-javascript-barcode.svg) -![downloads](https://img.shields.io/npm/dm/dynamsoft-javascript-barcode.svg) -![jsdelivr](https://img.shields.io/jsdelivr/npm/hm/dynamsoft-javascript-barcode.svg) -![vulnerabilities](https://img.shields.io/snyk/vulnerabilities/npm/dynamsoft-javascript-barcode.svg) - -Once integrated, your users can open your website in a browser, access their cameras and read barcodes directly from the video input. - -In this guide, you will learn step by step on how to integrate this library into your website. - -Table of Contents - -* [Hello World - Simplest Implementation](#hello-world---simplest-implementation) -* [Building your own page](#building-your-own-page) - * [Include the library](#include-the-library) - * [Configure the library](#configure-the-library) - * [Interact with the library](#interact-with-the-library) -* [API Documentation](#api-documentation) -* [System Requirements](#system-requirements) -* [Advanced Usage](#advanced-usage) -* [How to Upgrade](#how-to-upgrade) -* [FAQ](#faq) - -**Popular Examples** - -* Hello World - [Guide](#hello-world---simplest-implementation) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/master/1.hello-world/1.hello-world.html) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/1.hello-world.html?utm_source=guide) -* Angular App - [Guide](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/helloworld-angular.html?ver=9.0.0&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/master/1.hello-world/3.read-video-angular) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/3.read-video-angular/dist/hello-world/?utm_source=guide) -* React App - [Guide](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/helloworld-reactjs.html?ver=9.0.0&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/master/1.hello-world/4.read-video-react) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/4.read-video-react/build/?utm_source=guide) -* Vue App - [Guide](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/helloworld-vuejsv3.html?ver=9.0.0&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/master/1.hello-world/6.read-video-vue3) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/6.read-video-vue3/dist/?utm_source=guide) -* PWA App - [Guide](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/helloworld-pwa.html?ver=9.0.0&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/master/1.hello-world/10.read-video-pwa) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/10.read-video-pwa/helloworld-pwa.html?utm_source=guide) - -You can also: - -* Try the Official Demo - [Run](https://demo.dynamsoft.com/barcode-reader-js/?utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-demo) -* Try Online Examples - [Run](https://demo.dynamsoft.com/Samples/DBR/JS/index.html?utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples) - -## Hello World - Simplest Implementation - -Let's start with the "Hello World" example of the library which demonstrates how to use the minimum code to enable a web page to read barcodes from a live video stream. - -* Basic Requirements - * Internet connection - * [A supported browser](#system-requirements) - * Camera access - -### Step One: Check the code of the example - -The complete code of the "Hello World" example is shown below - -```html - - - - - - - - - -``` - -

- - Code in Github - -   - - Run via JSFiddle - -   - - Run in Dynamsoft - -   - - Download from Dynamsoft - -

- ------ - -#### About the code - -* `license`: This property specifies a license key. Read more on [Specify the license](#specify-the-license). - -* `createInstance()`: This method creates a `BarcodeScanner` object. This object can read barcodes directly from a video input with the help of its interactive UI (hidden by default) and the MediaDevices interface. - -* `onFrameRead`: This event is triggered every time the library finishes scanning a video frame. The `results` object contains all the barcode results that the library have found on this frame. In this example, we print the results to the browser console. - -* `onUniqueRead`: This event is triggered when the library finds a new barcode, which is not a duplicate among multiple frames. `txt` holds the barcode text value while `result` is an object that holds details of the barcode. In this example, an alert will be displayed for this new barcode. - -* `show()`: This method brings up the built-in UI of the `BarcodeScanner` object and starts scanning. - -### Step Two: Test the example - -Open the example page in a browser, allow the page to access your camera and the video will show up on the page. After that, you can point the camera at a barcode to read it. - -When a barcode is decoded, you will see the result text pop up and the barcode location will be highlighted in the video feed. - -*Note*: - -* Although the page should work properly when opened directly as a file ("file:///"), it's recommended that you deploy it to a web server before accessing it. Also, some browsers require a secure connection (HTTPS) to access the cameras, so deploying the page to a HTTPS website is the best choice. -* For first use, you may need to wait a few seconds for the library to initialize. -* The license "DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9" used in this sample is an online license and requires network connection to work. - -If the test doesn't go as expected, you can check out the [FAQ](#faq) or [contact us](https://www.dynamsoft.com/contact/?utm_source=guide). - -## Building your own page - -### Include the library - -#### Use a CDN - -The simplest way to include the library is to use either the [jsDelivr](https://jsdelivr.com/) or [UNPKG](https://unpkg.com/) CDN. The "hello world" example above uses **jsDelivr**. - -* jsDelivr - - ```html - - ``` - -* UNPKG - - ```html - - ``` - -#### Host the library yourself - -Besides using the CDN, you can also download the library and host its files on your own website / server before including it in your application. - -To download the library: - -* yarn - - ```cmd - yarn add dynamsoft-javascript-barcode - ``` - -* npm - - ```cmd - npm install dynamsoft-javascript-barcode --save - ``` - -Depending on how you downloaded the library and where you put it, you can typically include it like this: - -```html - -``` - -or - -```html - -``` - -Read more on [how to host the library](advanced-usage.md#hosting-the-library). - -### Configure the library - -Before using the library, you need to configure a few things. - -#### Specify the license - -The library requires a license to work, use the API `license` to specify a license key. - -```javascript -Dynamsoft.DBR.BarcodeScanner.license = "YOUR-LICENSE-KEY"; -``` - -To test the library, you can request a 30-day trial license via the Request a Trial License link. - -> If you registered for a Dynamsoft account and downloaded the library from the official site, Dynamsoft will generate a 30-day trial license for you and put the license key in all the downloaded samples. - -#### Specify the location of the "engine" files - -If the engine files (\*.worker.js, \*.wasm.js and \*.wasm, etc.) are not in the same location with the main library file (dbr.js), you can use the API `engineResourcePath` to specify the engine path, for example: - -```javascript -//The following code uses the jsDelivr CDN, feel free to change it to your own location of these files -Dynamsoft.DBR.BarcodeScanner.engineResourcePath = "https://cdn.jsdelivr.net/npm/dynamsoft-javascript-barcode@9.0.0/dist/"; -``` - -This configuration is usually required with frameworks like Angular or React where dbr.js is compiled into another file. - -### Interact with the library - -#### Create a `BarcodeScanner` object - -You can use one of two classes ( `BarcodeScanner` and `BarcodeReader` ) to interact with the library. `BarcodeReader` is a low-level class that processes images directly. `BarcodeScanner`, on the other hand, inherits from `BarcodeReader` and provides high-level APIs and a built-in GUI to allow continuous barcode scanning on video frames. We'll focus on `BarcodeScanner` in this guide. - -To use the library, we first create a `BarcodeScanner` object. - -```javascript -Dynamsoft.DBR.BarcodeScanner.license = "YOUR-LICENSE-KEY"; -let scanner = null; -try { - scanner = await Dynamsoft.DBR.BarcodeScanner.createInstance(); -} catch (ex) { - console.error(ex); -} -``` - -Tip: When creating a `BarcodeScanner` object within a function which may be called more than once, it's best to use a "helper" variable to avoid double creation such as `pScanner` in the following code - -```javascript -Dynamsoft.DBR.BarcodeScanner.license = "YOUR-LICENSE-KEY"; -let pScanner = null; -document.getElementById('btn-scan').addEventListener('click', async () => { - try { - const scanner = await (pScanner = pScanner || Dynamsoft.DBR.BarcodeScanner.createInstance()); - } catch (ex) { - console.error(ex); - } -}); -``` - -#### Configure the `BarcodeScanner` object - -Let's take a look at the following code snippets: - -```javascript -// set which camera and what resolution to use -let allCameras = await scanner.getAllCameras(); -await scanner.setCurrentCamera(allCameras[0].deviceId); -await scanner.setResolution(1280, 720); -``` - -```javascript -// set up the scanner behavior -let scanSettings = await scanner.getScanSettings(); -// disregard duplicated results found in a specified time period (in milliseconds) -scanSettings.duplicateForgetTime = 5000; -// set a scan interval in milliseconds so the library may release the CPU from time to time -// setting this value larger is also a simple way to save battery power and reduce device heating. -scanSettings.intervalTime = 100; -await scanner.updateScanSettings(scanSettings); -``` - -```javascript -// use one of the built-in RuntimeSetting templates: "single" (decode a single barcode, the default mode), "speed", "balance" and "coverage" -await scanner.updateRuntimeSettings("speed"); - -// make changes to the template. The code below demonstrates how to specify enabled symbologies -let runtimeSettings = await scanner.getRuntimeSettings(); -runtimeSettings.barcodeFormatIds = Dynamsoft.DBR.EnumBarcodeFormat.BF_ONED | Dynamsoft.DBR.EnumBarcodeFormat.BF_QR_CODE; -await scanner.updateRuntimeSettings(runtimeSettings); -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/yfkcajxz/) - -As you can see from the above code snippets, there are three types of configurations: - -* `get/updateVideoSettings`: Configures the data source, i.e., the camera. These settings include which camera to use, the resolution, etc. Learn more here. - -* `get/updateScanSettings`: Configures the behavior of the scanner which includes `duplicateForgetTime` and `intervalTime`, etc. - -* `get/updateRuntimeSettings`: Configures the decode engine with either a built-in template or a comprehensive `RuntimeSettings` object. For example, the following uses the built-in "speed" settings with updated `localizationModes`. - -> Find the full list of the runtime settings here. - - ```javascript - await barcodeScanner.updateRuntimeSettings("speed"); - //await barcodeScanner.updateRuntimeSettings("balance"); //alternative - //await barcodeScanner.updateRuntimeSettings("coverage"); //alternative - let settings = await barcodeScanner.getRuntimeSettings(); - settings.localizationModes = [ - Dynamsoft.DBR.EnumLocalizationMode.LM_CONNECTED_BLOCKS, - Dynamsoft.DBR.EnumLocalizationMode.LM_SCAN_DIRECTLY, - Dynamsoft.DBR.EnumLocalizationMode.LM_LINES, 0, 0, 0, 0, 0 - ]; - await barcodeScanner.updateRuntimeSettings(settings); - ``` - - Try in [JSFiddle](https://jsfiddle.net/DynamsoftTeam/f24h8c1m/). - - See also [settings samples](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/parameter-settings.html?ver=9.0.0&utm_source=guide). - -#### Customize the UI - -The built-in UI of the `BarcodeScanner` object is defined in the file `dist/dbr.ui.html` . There are a few ways to customize it: - -* Modify the file `dist/dbr.ui.html` directly. - - This option is only possible when you host this file on your own web server instead of using a CDN. - -* Copy the file `dist/dbr.ui.html` to your application, modify it and use the the API `defaultUIElementURL` to set it as the default UI. - - ```javascript - Dynamsoft.DBR.BarcodeScanner.defaultUIElementURL = "THE-URL-TO-THE-FILE"; - ``` - - > You must set `defaultUIElementURL` before you call `createInstance()` . - -* Append the default UI element to your page, customize it before showing it. - - ```html -
- ``` - - ```javascript - document.getElementById('div-ui-container').appendChild(scanner.getUIElement()); - document.getElementsByClassName('dce-btn-close')[0].hidden = true; // Hide the close button - ``` - -* Build the UI element into your own web page and specify it with the API `setUIElement(HTMLElement)`. - - * Embed the video - - ```html -
-
-
- - ``` - - > 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`. - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/2jzeq1r6/) - - * Add the camera list and resolution list - - If the class names for these lists match the default ones, `dce-sel-camera` and `dce-sel-resolution` , the library will automatically populate the lists and handle the camera/resolution switching. - - ```html - - ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/nbj75vxu/) - - ```html - - ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/25v08paf/) - - > By default, 8 hard-coded resolutions are populated as options. You can show only a custom set of options by hardcoding them. - - ```html - - ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/tnfjks4q/) - - > Generally, you need to provide a resolution that the camera supports. However, in case a camera does not support the specified resolution, it usually uses the nearest supported resolution. As a result, the selected resolution may not be the actual resolution used. In this case, add an option with the class name `dce-opt-gotResolution` (as shown above) and the library will then use it to show the actual resolution. - -See also [UI customization samples](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/ui-customization.html?ver=9.0.0&utm_source=guide). - -## API Documentation - -You can check out the detailed documentation about the APIs of the library at -[https://www.dynamsoft.com/barcode-reader/programming/javascript/api-reference/?ver=9.0.0](https://www.dynamsoft.com/barcode-reader/programming/javascript/api-reference/?ver=9.0.0). - -## System Requirements - -This library requires the following features which are supported by all modern mainstream browsers: - -* `WebAssembly`, `Blob`, `URL`/`createObjectURL`, `Web Workers` - - The above four features are required for the library to work. - -* `MediaDevices`/`getUserMedia` - - This API is only required for in-browser video streaming. If a browser does not support this API, the [Single Frame Mode](https://www.dynamsoft.com/barcode-reader/programming/javascript/api-reference/BarcodeScanner.html?ver=9.0.0&utm_source=guide#singleframemode) will be used automatically. If the API exists but doesn't work correctly, the Single Frame Mode can be used as an alternative way to access the camera. - -* `getSettings` - - This API inspects the video input which is a `MediaStreamTrack` object about its constrainable properties. - -The following table is a list of supported browsers based on the above requirements: - - Browser Name | Version - :-: | :-: - Chrome | v59+1 - Firefox | v52+ (v55+ on Android/iOS1) - Edge2 | v16+ - Safari3 | v11+ - - 1 iOS 14.3+ is required for camera video streaming in Chrome and Firefox or Apps using webviews. - - 2 On Edge, due to strict Same-origin policy, you must host the library files on the same domain as your web page. - - 3 Safari 11.2.2 ~ 11.2.6 are not supported. - -Apart from the browsers, the operating systems may impose some limitations of their own that could restrict the use of the library. Browser compatibility ultimately depends on whether the browser on that particular operating system supports the features listed above. - -## Advanced Usage - -In addition to the above basic settings, the library has many more settings and options that you can adjust to best suit your usage. To read more, please see [advanced usage](https://www.dynamsoft.com/barcode-reader/programming/javascript/user-guide/advanced-usage.html?ver=9.0.0&utm_source=guide). - -## How to Upgrade - -If you want to upgrade the library from an old version to a newer one, please see [how to upgrade](https://www.dynamsoft.com/barcode-reader/programming/javascript/upgrade-guide/?ver=9.0.0&utm_source=guide). - -## FAQ - -### Can I open the web page directly from the hard drive? - -Yes, for simple testing purposes, it's perfectly fine to open the file directly from the hard drive. However, you might encounter some issues in doing so (like unable to access the camera, etc.). The recommendation is to deploy this page to your web server and run it over **HTTPS**. If you don't have a ready-to-use web server but have a package manager like *npm* or *yarn*, you can set up a simple HTTP server in minutes. Check out [http-server on npm](https://www.npmjs.com/package/http-server). - -### Why can't I use my camera? - -If you open the web page as `file:///` or `http://` , the camera may not work and you see the following error in 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 equivalent error is: - -> Trying to call getUserMedia from an insecure document. - -You get this error because the API getUserMedia requires HTTPS to access the camera. - -To make sure your web application can access the camera, please configure your web server to support HTTPS. The following links may help. - -1. NGINX: Configuring HTTPS servers -2. IIS: Create a Self Signed Certificate in IIS -3. Tomcat: Setting Up SSL on Tomcat in 5 minutes -4. Node.js: npm tls - -> If you use Chrome or Firefox, you might not get the error because these two browsers allow camera access via `file:///` and `http://localhost`. However, our recommendation is that you deploy the web page to a web server that supports HTTPS. - -### Accounting for newline characters in the barcode result - -When it comes to HTML, newline characters ( `\n` ) are not interpreted as they normally would. Therefore, if a barcode result contains a newline character, and you display the result in an modal dialogue box or some other text elements, then the newline character will probably be ignored. - -There are two ways in which you can resolve this: - -1. Wrap the element used to display the result in a `
` element.
-2. Manually replace each `\n` character in the result with `
` diff --git a/programming-old/javascript/user-guide/index-v9.0.1.md b/programming-old/javascript/user-guide/index-v9.0.1.md deleted file mode 100644 index c9ce1886..00000000 --- a/programming-old/javascript/user-guide/index-v9.0.1.md +++ /dev/null @@ -1,469 +0,0 @@ ---- -layout: default-layout -title: v9.0.1 User Guide - Dynamsoft Barcode Reader JavaScript Edition -description: This is the user guide of Dynamsoft Barcode Reader JavaScript SDK. -keywords: user guide, javascript, js -breadcrumbText: User Guide -noTitleIndex: true -needGenerateH3Content: true -needAutoGenerateSidebar: true -permalink: /programming/javascript/user-guide/index-v9.0.1.html ---- - - - -# Barcode Reader for Your Website - -[Dynamsoft Barcode Reader JavaScript Edition](https://www.dynamsoft.com/barcode-reader/sdk-javascript/) is equipped with industry-leading algorithms for exceptional speed, accuracy and read rates in barcode reading. With its well-designed API, you can turn your web page into a barcode scanner with just a few lines of code. - -![version](https://img.shields.io/npm/v/dynamsoft-javascript-barcode.svg) -![downloads](https://img.shields.io/npm/dm/dynamsoft-javascript-barcode.svg) -![jsdelivr](https://img.shields.io/jsdelivr/npm/hm/dynamsoft-javascript-barcode.svg) -![vulnerabilities](https://img.shields.io/snyk/vulnerabilities/npm/dynamsoft-javascript-barcode.svg) - -Once integrated, your users can open your website in a browser, access their cameras and read barcodes directly from the video input. - -In this guide, you will learn step by step on how to integrate this library into your website. - -Table of Contents - -- [Barcode Reader for Your Website](#barcode-reader-for-your-website) - - [Hello World - Simplest Implementation](#hello-world---simplest-implementation) - - [Step One: Check the code of the example](#step-one-check-the-code-of-the-example) - - [About the code](#about-the-code) - - [Step Two: Test the example](#step-two-test-the-example) - - [Building your own page](#building-your-own-page) - - [Include the library](#include-the-library) - - [Use a CDN](#use-a-cdn) - - [Host the library yourself](#host-the-library-yourself) - - [Configure the library](#configure-the-library) - - [Specify the license](#specify-the-license) - - [Specify the location of the "engine" files](#specify-the-location-of-the-engine-files) - - [Interact with the library](#interact-with-the-library) - - [Create a `BarcodeScanner` object](#create-a-barcodescanner-object) - - [Customize the `BarcodeScanner` Settings (optional)](#customize-the-barcodescanner-settings-optional) - - [Customize the UI (optional)](#customize-the-ui-optional) - - [API Documentation](#api-documentation) - - [System Requirements](#system-requirements) - - [Advanced Usage](#advanced-usage) - - [How to Upgrade](#how-to-upgrade) - -**Popular Examples** - -* Hello World - [Guide](#hello-world---simplest-implementation) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.0.1/1.hello-world/1.hello-world.html) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/1.hello-world.html?ver=9.0.1&utm_source=guide) -* Angular App - [Guide](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/helloworld-angular.html?ver=9.0.1&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.0.1/1.hello-world/3.read-video-angular) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/3.read-video-angular/dist/hello-world/?ver=9.0.1&utm_source=guide) -* React App - [Guide](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/helloworld-reactjs.html?ver=9.0.1&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.0.1/1.hello-world/4.read-video-react) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/4.read-video-react/build/?ver=9.0.1&utm_source=guide) -* Vue App - [Guide](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/helloworld-vuejsv3.html?ver=9.0.1&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.0.1/1.hello-world/6.read-video-vue3) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/6.read-video-vue3/dist/?ver=9.0.1&utm_source=guide) -* PWA App - [Guide](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/helloworld-pwa.html?ver=9.0.1&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.0.1/1.hello-world/10.read-video-pwa) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/10.read-video-pwa/helloworld-pwa.html?ver=9.0.1&utm_source=guide) -* Read Driver Licenses - [Guide](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/use-cases.html?ver=latest#read-the-pdf417-barcode-on-the-drivers-license?ver=9.0.1&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.0.1/4.use-case/2.read-a-drivers-license.html) \| [Run](https://demo.dynamsoft.com/samples/dbr/js/4.use-case/2.read-a-drivers-license.html?ver=9.0.1&utm_source=guide) -* Fill A Form - [Guide](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/use-cases.html?ver=latest#read-barcodes-and-fill-form-fields?ver=9.0.1&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.0.1/4.use-case/1.fill-a-form-with-barcode-reading.html) \| [Run](https://demo.dynamsoft.com/samples/dbr/js/4.use-case/1.fill-a-form-with-barcode-reading.html?ver=9.0.1&utm_source=guide) - -You can also: - -* Try the Official Demo - [Run](https://demo.dynamsoft.com/barcode-reader-js/?ver=9.0.1&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-demo/) -* Try Online Examples - [Run](https://demo.dynamsoft.com/Samples/DBR/JS/index.html?ver=9.0.1&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/v9.0.1/) - -## Hello World - Simplest Implementation - -Let's start with the "Hello World" example of the library which demonstrates how to use the minimum code to enable a web page to read barcodes from a live video stream. - -* Basic Requirements - * Internet connection - * [A supported browser](#system-requirements) - * Camera access - -### Step One: Check the code of the example - -The complete code of the "Hello World" example is shown below - -```html - - - - - - - - - -``` - -

- - Code in Github - -   - - Run via JSFiddle - -   - - Run in Dynamsoft - -

- ------ - -#### About the code - -* `license`: This property specifies a license key. Note that the license "DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9" used in this example is an online license and requires network connection to work. Read more on [Specify the license](#specify-the-license). - -* `createInstance()`: This method creates a `BarcodeScanner` object. This object can read barcodes directly from a video input with the help of its interactive UI (hidden by default) and the MediaDevices interface. - -* `onFrameRead`: This event is triggered every time the library finishes scanning a video frame. The `results` object contains all the barcode results that the library have found on this frame. In this example, we print the results to the browser console. - -* `onUniqueRead`: This event is triggered when the library finds a new barcode, which is not a duplicate among multiple frames. `txt` holds the barcode text value while `result` is an object that holds details of the barcode. In this example, an alert will be displayed for this new barcode. - -* `show()`: This method brings up the built-in UI of the `BarcodeScanner` object and starts scanning. - -### Step Two: Test the example - -To test the example, you can open the copy deployed to Dynamsoft Server here. You will be asked to allow access to your camera, after which the video will be displayed on the page. After that, you can point the camera at a barcode to read it. - -When a barcode is decoded, you will see the result text pop up and the barcode location will be highlighted in the video feed. - -Alternatively, you can make a local test simply by taking the code in step 1, pasting it in a file with the name "hello-world.html" and open it in a browser. - -*Note*: - -If you open the web page as `file:///` or `http://` , the camera may not work correctly because the API getUserMedia usually requires HTTPS to access the camera. - -To make sure your web application can access the camera, please configure your web server to support HTTPS. The following links may help. - -1. NGINX: Configuring HTTPS servers -2. IIS: Create a Self Signed Certificate in IIS -3. Tomcat: Setting Up SSL on Tomcat in 5 minutes -4. Node.js: npm tls - -If the test doesn't go as expected, you can [contact us](https://www.dynamsoft.com/contact/?ver=9.0.1&utm_source=guide). - -## Building your own page - -### Include the library - -#### Use a CDN - -The simplest way to include the library is to use either the [jsDelivr](https://jsdelivr.com/) or [UNPKG](https://unpkg.com/) CDN. The "hello world" example above uses **jsDelivr**. - -* jsDelivr - - ```html - - ``` - -* UNPKG - - ```html - - ``` - -#### Host the library yourself - -Besides using the CDN, you can also download the library and host its files on your own website / server before including it in your application. - -Options to download the library: - -* From the website - - Download the JavaScript Package - -* yarn - - ```cmd - yarn add dynamsoft-javascript-barcode - ``` - -* npm - - ```cmd - npm install dynamsoft-javascript-barcode --save - ``` - -Depending on how you downloaded the library and where you put it, you can typically include it like this: - -```html - -``` - -or - -```html - -``` - -Read more on [how to host the library](https://www.dynamsoft.com/barcode-reader/programming/javascript/user-guide/advanced-usage.html?ver=9.0.1&utm_source=guide&product=dbr&package=js#hosting-the-library). - -### Configure the library - -Before using the library, you need to configure a few things. - -#### Specify the license - -The library requires a license to work, use the API `license` to specify a license key. - -```javascript -Dynamsoft.DBR.BarcodeScanner.license = "YOUR-LICENSE-KEY"; -``` - -To test the library, you can request a 30-day trial license via the Request a Trial License link. - -> If you registered a Dynamsoft account and downloaded the library from the official website, Dynamsoft will generate a 30-day trial license for you and put the license key into all the samples that come with the library. - -#### Specify the location of the "engine" files - -This is usually only required with frameworks like Angular or React, etc. where dbr.js is compiled into another file. - -The purpose is to tell the library where to find the engine files (\*.worker.js, \*.wasm.js and \*.wasm, etc.). The API is called `engineResourcePath`: - -```javascript -//The following code uses the jsDelivr CDN, feel free to change it to your own location of these files -Dynamsoft.DBR.BarcodeScanner.engineResourcePath = "https://cdn.jsdelivr.net/npm/dynamsoft-javascript-barcode@9.0.1/dist/"; -``` - -### Interact with the library - -#### Create a `BarcodeScanner` object - -You can use one of two classes ( `BarcodeScanner` and `BarcodeReader` ) to interact with the library. `BarcodeReader` is a low-level class that processes images directly. `BarcodeScanner` , on the other hand, inherits from `BarcodeReader` and provides high-level APIs and a built-in GUI to allow continuous barcode scanning on video frames. We'll focus on `BarcodeScanner` in this guide. - -To use the library, we first create a `BarcodeScanner` object. - -```javascript -Dynamsoft.DBR.BarcodeScanner.license = "YOUR-LICENSE-KEY"; -let scanner = null; -try { - scanner = await Dynamsoft.DBR.BarcodeScanner.createInstance(); -} catch (ex) { - console.error(ex); -} -``` - -Tip: When creating a `BarcodeScanner` object within a function which may be called more than once, it's best to use a "helper" variable to avoid double creation such as `pScanner` in the following code - -```javascript -Dynamsoft.DBR.BarcodeScanner.license = "YOUR-LICENSE-KEY"; -let pScanner = null; -document.getElementById('btn-scan').addEventListener('click', async () => { - try { - const scanner = await (pScanner = pScanner || Dynamsoft.DBR.BarcodeScanner.createInstance()); - } catch (ex) { - console.error(ex); - } -}); -``` - -#### Customize the `BarcodeScanner` Settings (optional) - -Let's take a look at the following code snippets: - -```javascript -// Sets which camera and what resolution to use -let allCameras = await scanner.getAllCameras(); -await scanner.setCurrentCamera(allCameras[0].deviceId); -await scanner.setResolution(1280, 720); -``` - -```javascript -// Sets up the scanner behavior -let scanSettings = await scanner.getScanSettings(); -// Disregards duplicated results found in a specified time period (in milliseconds) -scanSettings.duplicateForgetTime = 5000; -// Sets a scan interval in milliseconds so the library may release the CPU from time to time -// (setting this value larger is a simple way to save battery power and reduce device heating). -scanSettings.intervalTime = 100; -await scanner.updateScanSettings(scanSettings); -``` - -```javascript -// Uses one of the built-in RuntimeSetting templates: "single" (decode a single barcode, the default mode), "speed", "balance" and "coverage" -await scanner.updateRuntimeSettings("speed"); - -// Makes changes to the template. The code below demonstrates how to specify enabled symbologies -let runtimeSettings = await scanner.getRuntimeSettings(); -runtimeSettings.barcodeFormatIds = Dynamsoft.DBR.EnumBarcodeFormat.BF_ONED | Dynamsoft.DBR.EnumBarcodeFormat.BF_QR_CODE; -await scanner.updateRuntimeSettings(runtimeSettings); -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/yfkcajxz/) - -As you can see from the above code snippets, there are three types of configurations: - -* Customize the data source: This configuration includes which camera to use, the preferred resolution, etc. Learn more here. - -* `get/updateScanSettings`: Configures the behavior of the scanner which includes `duplicateForgetTime` and `intervalTime`, etc. - -* `get/updateRuntimeSettings`: Configures the decode engine with either a built-in template or a comprehensive `RuntimeSettings` object. For example, the following uses the built-in "speed" settings with updated `localizationModes`. - -> Find the full list of the runtime settings here. - - ```javascript - await barcodeScanner.updateRuntimeSettings("speed"); - //await barcodeScanner.updateRuntimeSettings("balance"); //alternative - //await barcodeScanner.updateRuntimeSettings("coverage"); //alternative - let settings = await barcodeScanner.getRuntimeSettings(); - settings.localizationModes = [ - Dynamsoft.DBR.EnumLocalizationMode.LM_CONNECTED_BLOCKS, - Dynamsoft.DBR.EnumLocalizationMode.LM_SCAN_DIRECTLY, - Dynamsoft.DBR.EnumLocalizationMode.LM_LINES, 0, 0, 0, 0, 0 - ]; - await barcodeScanner.updateRuntimeSettings(settings); - ``` - - Try in [JSFiddle](https://jsfiddle.net/DynamsoftTeam/f24h8c1m/). - - See also [settings samples](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/parameter-settings.html?ver=9.0.1&utm_source=guide). - -### Customize the UI (optional) - -The built-in UI of the `BarcodeScanner` object is defined in the file `dist/dbr.ui.html` . There are a few ways to customize it: - -* Modify the file `dist/dbr.ui.html` directly. - - This option is only possible when you host this file on your own web server instead of using a CDN. - -* Copy the file `dist/dbr.ui.html` to your application, modify it and use the the API `defaultUIElementURL` to set it as the default UI. - - ```javascript - Dynamsoft.DBR.BarcodeScanner.defaultUIElementURL = "THE-URL-TO-THE-FILE"; - ``` - - > You must set `defaultUIElementURL` before you call `createInstance()` . - -* Append the default UI element to your page, customize it before showing it. - - ```html -
- ``` - - ```javascript - document.getElementById('div-ui-container').appendChild(scanner.getUIElement()); - document.getElementsByClassName('dce-btn-close')[0].hidden = true; // Hide the close button - ``` - -* Build the UI element into your own web page and specify it with the API `setUIElement(HTMLElement)`. - - * Embed the video - - ```html -
-
-
- - ``` - - > 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` . - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/2jzeq1r6/) - - * Add the camera list and resolution list - - If the class names for these lists match the default ones, `dce-sel-camera` and `dce-sel-resolution` , the library will automatically populate the lists and handle the camera/resolution switching. - - ```html -
-
-
-
- ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/nbj75vxu/) - - ```html -
- - -
-
-
- ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/25v08paf/) - - > By default, 8 hard-coded resolutions are populated as options. You can show only a custom set of options by hardcoding them. - - ```html - - ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/tnfjks4q/) - - > Generally, you need to provide a resolution that the camera supports. However, in case a camera does not support the specified resolution, it usually uses the nearest supported resolution. As a result, the selected resolution may not be the actual resolution used. In this case, add an option with the class name `dce-opt-gotResolution` (as shown above) and the library will then use it to show the actual resolution. - -See also [UI customization samples](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/ui-customization.html?ver=9.0.1&utm_source=guide). - -## API Documentation - -You can check out the detailed documentation about the APIs of the library at -[https://www.dynamsoft.com/barcode-reader/programming/javascript/api-reference/?ver=9.0.1](https://www.dynamsoft.com/barcode-reader/programming/javascript/api-reference/?ver=9.0.1). - -## System Requirements - -This library requires the following features which are supported by all modern mainstream browsers: - -* `WebAssembly`, `Blob`, `URL`/`createObjectURL`, `Web Workers` - - The above four features are required for the library to work. - -* `MediaDevices`/`getUserMedia` - - This API is only required for in-browser video streaming. If a browser does not support this API, the [Single Frame Mode](https://www.dynamsoft.com/barcode-reader/programming/javascript/api-reference/BarcodeScanner.html?ver=9.0.1&utm_source=guide#singleframemode) will be used automatically. If the API exists but doesn't work correctly, the Single Frame Mode can be used as an alternative way to access the camera. - -* `getSettings` - - This API inspects the video input which is a `MediaStreamTrack` object about its constrainable properties. - -The following table is a list of supported browsers based on the above requirements: - - Browser Name | Version - :-: | :-: - Chrome | v59+1 - Firefox | v52+ (v55+ on Android/iOS1) - Edge2 | v16+ - Safari3 | v11+ - - 1 iOS 14.3+ is required for camera video streaming in Chrome and Firefox or Apps using webviews. - - 2 On Edge, due to strict Same-origin policy, you must host the library files on the same domain as your web page. - - 3 Safari 11.2.2 ~ 11.2.6 are not supported. - -Apart from the browsers, the operating systems may impose some limitations of their own that could restrict the use of the library. Browser compatibility ultimately depends on whether the browser on that particular operating system supports the features listed above. - -## Advanced Usage - -In addition to the above basic settings, the library has many more settings and options that you can adjust to best suit your usage. To read more, please see [advanced usage](https://www.dynamsoft.com/barcode-reader/programming/javascript/user-guide/advanced-usage.html?ver=9.0.1&utm_source=guide). - -## How to Upgrade - -If you want to upgrade the library from an old version to a newer one, please see [how to upgrade](https://www.dynamsoft.com/barcode-reader/programming/javascript/upgrade-guide/?ver=9.0.1&utm_source=guide). diff --git a/programming-old/javascript/user-guide/index-v9.0.2.md b/programming-old/javascript/user-guide/index-v9.0.2.md deleted file mode 100644 index 545ffd28..00000000 --- a/programming-old/javascript/user-guide/index-v9.0.2.md +++ /dev/null @@ -1,486 +0,0 @@ ---- -layout: default-layout -title: v9.0.2 User Guide - Dynamsoft Barcode Reader JavaScript Edition -description: This is the user guide of Dynamsoft Barcode Reader JavaScript SDK. -keywords: user guide, javascript, js -breadcrumbText: User Guide -noTitleIndex: true -needGenerateH3Content: true -needAutoGenerateSidebar: true -permalink: /programming/javascript/user-guide/index-v9.0.2.html ---- - - - -# Barcode Reader for Your Website - User Guide - -[Dynamsoft Barcode Reader JavaScript Edition](https://www.dynamsoft.com/barcode-reader/sdk-javascript/) (DBR-JS) is equipped with industry-leading algorithms for exceptional speed, accuracy and read rates in barcode reading. Using its well-designed API, you can turn your web page into a barcode scanner with just a few lines of code. - -![version](https://img.shields.io/npm/v/dynamsoft-javascript-barcode.svg) -![downloads](https://img.shields.io/npm/dm/dynamsoft-javascript-barcode.svg) -![jsdelivr](https://img.shields.io/jsdelivr/npm/hm/dynamsoft-javascript-barcode.svg) -![vulnerabilities](https://img.shields.io/snyk/vulnerabilities/npm/dynamsoft-javascript-barcode.svg) - -Once the DBR-JS SDK gets integrated into your web page, your users can access a camera via the browser and read barcodes directly from its video input. - -In this guide, you will learn step by step on how to integrate the DBR-JS SDK into your website. - -Table of Contents - -- [Barcode Reader for Your Website - User Guide](#barcode-reader-for-your-website---user-guide) - - [Hello World - Simplest Implementation](#hello-world---simplest-implementation) - - [Understand the code](#understand-the-code) - - [About the code](#about-the-code) - - [Run the example](#run-the-example) - - [Building your own page](#building-your-own-page) - - [Include the SDK](#include-the-sdk) - - [Use a CDN](#use-a-cdn) - - [Host the SDK yourself](#host-the-sdk-yourself) - - [Configure the SDK](#configure-the-sdk) - - [Specify the license](#specify-the-license) - - [Specify the location of the "engine" files](#specify-the-location-of-the-engine-files) - - [Interact with the SDK](#interact-with-the-sdk) - - [Create a `BarcodeScanner` object](#create-a-barcodescanner-object) - - [Customize the `BarcodeScanner` Settings (optional)](#customize-the-barcodescanner-settings-optional) - - [Customize the UI (optional)](#customize-the-ui-optional) - - [API Documentation](#api-documentation) - - [System Requirements](#system-requirements) - - [How to Upgrade](#how-to-upgrade) - - [Next Steps](#next-steps) - -**Popular Examples** - -* Hello World - [Guide](#hello-world---simplest-implementation) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.0.2/1.hello-world/1.hello-world.html) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/1.hello-world.html?ver=9.0.2&utm_source=guide) -* Angular App - [Guide](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/helloworld-angular.html?ver=9.0.2&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.0.2/1.hello-world/3.read-video-angular) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/3.read-video-angular/dist/hello-world/?ver=9.0.2&utm_source=guide) -* React App - [Guide](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/helloworld-reactjs.html?ver=9.0.2&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.0.2/1.hello-world/4.read-video-react) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/4.read-video-react/build/?ver=9.0.2&utm_source=guide) -* Vue App - [Guide](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/helloworld-vuejsv3.html?ver=9.0.2&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.0.2/1.hello-world/6.read-video-vue3) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/6.read-video-vue3/dist/?ver=9.0.2&utm_source=guide) -* PWA App - [Guide](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/helloworld-pwa.html?ver=9.0.2&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.0.2/1.hello-world/10.read-video-pwa) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/10.read-video-pwa/helloworld-pwa.html?ver=9.0.2&utm_source=guide) -* Read Driver Licenses - [Guide](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/use-cases.html?ver=latest#read-the-pdf417-barcode-on-the-drivers-license?ver=9.0.2&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.0.2/4.use-case/2.read-a-drivers-license.html) \| [Run](https://demo.dynamsoft.com/samples/dbr/js/4.use-case/2.read-a-drivers-license.html?ver=9.0.2&utm_source=guide) -* Fill A Form - [Guide](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/use-cases.html?ver=latest#read-barcodes-and-fill-form-fields?ver=9.0.2&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.0.2/4.use-case/1.fill-a-form-with-barcode-reading.html) \| [Run](https://demo.dynamsoft.com/samples/dbr/js/4.use-case/1.fill-a-form-with-barcode-reading.html?ver=9.0.2&utm_source=guide) - -You can also: - -* Try the Official Demo - [Run](https://demo.dynamsoft.com/barcode-reader-js/?ver=9.0.2&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-demo/) -* Try Online Examples - [Run](https://demo.dynamsoft.com/Samples/DBR/JS/index.html?ver=9.0.2&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/v9.0.2/) - -## Hello World - Simplest Implementation - -Let's start with the "Hello World" example of the DBR-JS SDK which demonstrates how to use the minimum code to enable a web page to read barcodes from a live video stream. - -* Basic Requirements - * Internet connection - * [A supported browser](#system-requirements) - * Camera access - -### Understand the code - -The complete code of the "Hello World" example is shown below - -```html - - - - - - - - - -``` - -

- - Code in Github - -   - - Run via JSFiddle - -   - - Run in Dynamsoft - -

- ------ - -#### About the code - -* `license`: This property specifies a license key. Note that the license "DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9" used in this example is an online license and requires network connection to work. Read more on [Specify the license](#specify-the-license). - -* `createInstance()`: This method creates a `BarcodeScanner` object. This object can read barcodes directly from a video input with the help of its interactive UI (hidden by default) and the MediaDevices interface. - -* `onFrameRead`: This event is triggered every time the SDK finishes scanning a video frame. The `results` object contains all the barcode results that the SDK have found on this frame. In this example, we print the results to the browser console. - -* `onUniqueRead`: This event is triggered when the SDK finds a new barcode, which is not a duplicate among multiple frames. `txt` holds the barcode text value while `result` is an object that holds details of the barcode. In this example, an alert will be displayed for this new barcode. - -* `show()`: This method brings up the built-in UI of the `BarcodeScanner` object and starts scanning. - -### Run the example - -You can run the example deployed to the Dynamsoft Demo Server or test it with JSFiddle code editor. You will be asked to allow access to your camera, after which the video will be displayed on the page. After that, you can point the camera at a barcode to read it. - -When a barcode is decoded, you will see the result text pop up and the barcode location will be highlighted in the video feed. - -Alternatively, you can make a local test simply by taking the code in step 1, pasting it in a file with the name "hello-world.html" and open it in a browser. - -*Note*: - -If you open the web page as `file:///` or `http://` , the camera may not work correctly because the API getUserMedia usually requires HTTPS to access the camera. - -To make sure your web application can access the camera, please configure your web server to support HTTPS. The following links may help. - -1. NGINX: Configuring HTTPS servers -2. IIS: Create a Self Signed Certificate in IIS -3. Tomcat: Setting Up SSL on Tomcat in 5 minutes -4. Node.js: npm tls - -If the test doesn't go as expected, you can [contact us](https://www.dynamsoft.com/contact/?ver=9.0.2&utm_source=guide). - -## Building your own page - -### Include the SDK - -#### Use a CDN - -The simplest way to include the SDK is to use either the [jsDelivr](https://jsdelivr.com/) or [UNPKG](https://unpkg.com/) CDN. The "hello world" example above uses **jsDelivr**. - -* jsDelivr - - ```html - - ``` - -* UNPKG - - ```html - - ``` - -#### Host the SDK yourself - -Besides using the CDN, you can also download the SDK and host its files on your own website / server before including it in your application. - -Options to download the SDK: - -* From the website - - Download the JavaScript Package - -* yarn - - ```cmd - yarn add dynamsoft-javascript-barcode - ``` - -* npm - - ```cmd - npm install dynamsoft-javascript-barcode --save - ``` - -Depending on how you downloaded the SDK and how you intend to use it, you can typically include it like this: - -```html - -``` - -or - -```html - -``` - -or - -```typescript -import { BarcodeScanner } from 'dynamsoft-javascript-barcode'; -``` - -### Configure the SDK - -Before using the SDK, you need to configure a few things. - -#### Specify the license - -The SDK requires a license to work, use the API `license` to specify a license key. - -```javascript -Dynamsoft.DBR.BarcodeScanner.license = "YOUR-LICENSE-KEY"; -``` - -To test the SDK, you can request a 30-day trial license via the Request a Trial License link. - -> If you registered a Dynamsoft account and downloaded the SDK from the official website, Dynamsoft will automatically generate a 30-day trial license for you and put the license key into all the samples that come with the SDK. - -#### Specify the location of the "engine" files - -This is usually only required with frameworks like Angular or React, etc. where dbr.js is compiled into another file. - -The purpose is to tell the SDK where to find the engine files (\*.worker.js, \*.wasm.js and \*.wasm, etc.). The API is called `engineResourcePath`: - -```javascript -//The following code uses the jsDelivr CDN, feel free to change it to your own location of these files -Dynamsoft.DBR.BarcodeScanner.engineResourcePath = "https://cdn.jsdelivr.net/npm/dynamsoft-javascript-barcode@9.0.2/dist/"; -``` - -### Interact with the SDK - -#### Create a `BarcodeScanner` object - -You can use one of two classes ( `BarcodeScanner` and `BarcodeReader` ) to interact with the SDK. `BarcodeReader` is a low-level class that processes images directly. `BarcodeScanner` , on the other hand, inherits from `BarcodeReader` and provides high-level APIs and a built-in GUI to allow continuous barcode scanning on video frames. We'll focus on `BarcodeScanner` in this guide. - -To use the SDK, we first create a `BarcodeScanner` object. - -```javascript -Dynamsoft.DBR.BarcodeScanner.license = "YOUR-LICENSE-KEY"; -let scanner = null; -try { - scanner = await Dynamsoft.DBR.BarcodeScanner.createInstance(); -} catch (ex) { - console.error(ex); -} -``` - -Tip: When creating a `BarcodeScanner` object within a function which may be called more than once, it's best to use a "helper" variable to avoid double creation such as `pScanner` in the following code - -```javascript -Dynamsoft.DBR.BarcodeScanner.license = "YOUR-LICENSE-KEY"; -let pScanner = null; -document.getElementById('btn-scan').addEventListener('click', async () => { - try { - const scanner = await (pScanner = pScanner || Dynamsoft.DBR.BarcodeScanner.createInstance()); - } catch (ex) { - console.error(ex); - } -}); -``` - -#### Customize the `BarcodeScanner` Settings (optional) - -Let's take a look at the following code snippets: - -```javascript -// Sets which camera and what resolution to use -let allCameras = await scanner.getAllCameras(); -await scanner.setCurrentCamera(allCameras[0].deviceId); -await scanner.setResolution(1280, 720); -``` - -```javascript -// Sets up the scanner behavior -let scanSettings = await scanner.getScanSettings(); -// Disregards duplicated results found in a specified time period (in milliseconds) -scanSettings.duplicateForgetTime = 5000; -// Sets a scan interval in milliseconds so the SDK may release the CPU from time to time -// (setting this value larger is a simple way to save battery power and reduce device heating). -scanSettings.intervalTime = 100; -await scanner.updateScanSettings(scanSettings); -``` - -```javascript -// Uses one of the built-in RuntimeSetting templates: "single" (decode a single barcode, the default mode), "speed", "balance" and "coverage" -await scanner.updateRuntimeSettings("speed"); - -// Makes changes to the template. The code below demonstrates how to specify enabled symbologies -let runtimeSettings = await scanner.getRuntimeSettings(); -runtimeSettings.barcodeFormatIds = Dynamsoft.DBR.EnumBarcodeFormat.BF_ONED | Dynamsoft.DBR.EnumBarcodeFormat.BF_QR_CODE; -await scanner.updateRuntimeSettings(runtimeSettings); -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/yfkcajxz/) - -As you can see from the above code snippets, there are three types of configurations: - -* Customize the data source: This configuration includes which camera to use, the preferred resolution, etc. Learn more here. - -* `get/updateScanSettings`: Configures the behavior of the scanner which includes `duplicateForgetTime` and `intervalTime`, etc. - -* `get/updateRuntimeSettings`: Configures the decode engine with either a built-in template or a comprehensive `RuntimeSettings` object. For example, the following uses the built-in "speed" settings with updated `localizationModes`. - - ```javascript - await barcodeScanner.updateRuntimeSettings("speed"); - //await barcodeScanner.updateRuntimeSettings("balance"); //alternative - //await barcodeScanner.updateRuntimeSettings("coverage"); //alternative - let settings = await barcodeScanner.getRuntimeSettings(); - settings.localizationModes = [ - Dynamsoft.DBR.EnumLocalizationMode.LM_CONNECTED_BLOCKS, - Dynamsoft.DBR.EnumLocalizationMode.LM_SCAN_DIRECTLY, - Dynamsoft.DBR.EnumLocalizationMode.LM_LINES, 0, 0, 0, 0, 0 - ]; - await barcodeScanner.updateRuntimeSettings(settings); - ``` - - Try in [JSFiddle](https://jsfiddle.net/DynamsoftTeam/f24h8c1m/). - - See also [settings samples](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/parameter-settings.html?ver=9.0.2&utm_source=guide). - -> Find the full list of the runtime settings here. - -### Customize the UI (optional) - -The built-in UI of the `BarcodeScanner` object is defined in the file `dist/dbr.ui.html` . There are a few ways to customize it: - -* Modify the file `dist/dbr.ui.html` directly. - - This option is only possible when you host this file on your own web server instead of using a CDN. - -* Copy the file `dist/dbr.ui.html` to your application, modify it and use the the API `defaultUIElementURL` to set it as the default UI. - - ```javascript - Dynamsoft.DBR.BarcodeScanner.defaultUIElementURL = "THE-URL-TO-THE-FILE"; - ``` - - > You must set `defaultUIElementURL` before you call `createInstance()` . - -* Append the default UI element to your page, customize it before showing it. - - ```html -
- ``` - - ```javascript - document.getElementById('div-ui-container').appendChild(scanner.getUIElement()); - document.getElementsByClassName('dce-btn-close')[0].hidden = true; // Hide the close button - ``` - -* Build the UI element from scratch and connect it to the SDK with the API `setUIElement(HTMLElement)`. - - * Embed the video - - ```html -
-
-
- - ``` - - > 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` . - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/2jzeq1r6/) - - * Add the camera list and resolution list - - If the class names for these lists match the default ones, `dce-sel-camera` and `dce-sel-resolution` , the SDK will automatically populate the lists and handle the camera/resolution switching. - - ```html -
-
-
-
- ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/nbj75vxu/) - - ```html -
- - -
-
-
- ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/25v08paf/) - - > By default, 8 hard-coded resolutions are populated as options. You can show only a custom set of options by hardcoding them. - - ```html - - ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/tnfjks4q/) - - > Generally, you need to provide a resolution that the camera supports. However, in case a camera does not support the specified resolution, it usually uses the nearest supported resolution. As a result, the selected resolution may not be the actual resolution used. In this case, add an option with the class name `dce-opt-gotResolution` (as shown above) and the SDK will then use it to show the actual resolution. - - See also [UI customization samples](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/ui-customization.html?ver=9.0.2&utm_source=guide). - -## API Documentation - -You can check out the detailed documentation about the APIs of the SDK at -[https://www.dynamsoft.com/barcode-reader/programming/javascript/api-reference/?ver=9.0.2](https://www.dynamsoft.com/barcode-reader/programming/javascript/api-reference/?ver=9.0.2). - -## System Requirements - -DBR requires the following features to work: - -* Secure context (HTTPS deployment) - - When deploying your application / website for production, make sure to serve it via a secure HTTPS connection. This is required for two reasons - - * Access to the camera video stream is only granted in a security context. Most browsers impose this restriction. - > Some browsers like Chrome may grant the access for `http://127.0.0.1` and `http://localhost` or even for pages opened directly from the local disk (`file:///...`). This can be helpful for temporary development and test. - - * Dynamsoft License requires a secure context to work. - -* `WebAssembly`, `Blob`, `URL`/`createObjectURL`, `Web Workers` - - The above four features are required for the SDK to work. - -* `MediaDevices`/`getUserMedia` - - This API is only required for in-browser video streaming. If a browser does not support this API, the [Single Frame Mode](https://www.dynamsoft.com/barcode-reader/programming/javascript/api-reference/BarcodeScanner.html?ver=9.0.2&utm_source=guide#singleframemode) will be used automatically. If the API exists but doesn't work correctly, the Single Frame Mode can be used as an alternative way to access the camera. - -* `getSettings` - - This API inspects the video input which is a `MediaStreamTrack` object about its constrainable properties. - -The following table is a list of supported browsers based on the above requirements: - - Browser Name | Version - :-: | :-: - Chrome | v59+1 - Firefox | v52+ (v55+ on Android/iOS1) - Edge2 | v16+ - Safari3 | v11+ - - 1 iOS 14.3+ is required for camera video streaming in Chrome and Firefox or Apps using webviews. - - 2 On Edge, due to strict Same-origin policy, you must host the SDK files on the same domain as your web page. - - 3 Safari v11.x already has the required features, but it has many other issues, so we recommend v12+. - -Apart from the browsers, the operating systems may impose some limitations of their own that could restrict the use of the SDK. Browser compatibility ultimately depends on whether the browser on that particular operating system supports the features listed above. - -## How to Upgrade - -If you want to upgrade the SDK from an old version to a newer one, please see [how to upgrade](https://www.dynamsoft.com/barcode-reader/programming/javascript/upgrade-guide/?ver=9.0.2&utm_source=guide). - -## Next Steps - -Now that you have got the SDK integrated, you can choose to move forward in the following directions - -1. Check out the [Official Samples and Demo](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/index.html?ver=latest) -2. Learn how to make use of the [SDK features](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/user-guide/explore-features/index.html?ver=latest) -3. See how the SDK works in [Popular Use Cases](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/user-guide/use-cases/index.html?ver=latest) diff --git a/programming-old/javascript/user-guide/index-v9.2.12.md b/programming-old/javascript/user-guide/index-v9.2.12.md deleted file mode 100644 index ba5e63f6..00000000 --- a/programming-old/javascript/user-guide/index-v9.2.12.md +++ /dev/null @@ -1,492 +0,0 @@ ---- -layout: default-layout -title: v9.2.12 User Guide - Dynamsoft Barcode Reader JavaScript Edition -description: This is the user guide of Dynamsoft Barcode Reader JavaScript SDK. -keywords: user guide, javascript, js -breadcrumbText: User Guide -noTitleIndex: true -needGenerateH3Content: true -needAutoGenerateSidebar: true -permalink: /programming/javascript/user-guide/index-v9.2.12.html ---- - - - -# Barcode Reader for Your Website - User Guide - -[Dynamsoft Barcode Reader JavaScript Edition](https://www.dynamsoft.com/barcode-reader/sdk-javascript/) (DBR-JS) is equipped with industry-leading algorithms for exceptional speed, accuracy and read rates in barcode reading. Using its well-designed API, you can turn your web page into a barcode scanner with just a few lines of code. - -![version](https://img.shields.io/npm/v/dynamsoft-javascript-barcode.svg) -![downloads](https://img.shields.io/npm/dm/dynamsoft-javascript-barcode.svg) -![jsdelivr](https://img.shields.io/jsdelivr/npm/hm/dynamsoft-javascript-barcode.svg) -![vulnerabilities](https://img.shields.io/snyk/vulnerabilities/npm/dynamsoft-javascript-barcode.svg) - -Once the DBR-JS SDK gets integrated into your web page, your users can access a camera via the browser and read barcodes directly from its video input. - -In this guide, you will learn step by step on how to integrate the DBR-JS SDK into your website. - -Table of Contents - -- [Barcode Reader for Your Website - User Guide](#barcode-reader-for-your-website---user-guide) - - [Hello World - Simplest Implementation](#hello-world---simplest-implementation) - - [Understand the code](#understand-the-code) - - [About the code](#about-the-code) - - [Run the example](#run-the-example) - - [Building your own page](#building-your-own-page) - - [Include the SDK](#include-the-sdk) - - [Use a CDN](#use-a-cdn) - - [Host the SDK yourself](#host-the-sdk-yourself) - - [Configure the SDK](#configure-the-sdk) - - [Specify the license](#specify-the-license) - - [Specify the location of the "engine" files](#specify-the-location-of-the-engine-files) - - [Interact with the SDK](#interact-with-the-sdk) - - [Create a `BarcodeScanner` object](#create-a-barcodescanner-object) - - [Customize the `BarcodeScanner` Settings (optional)](#customize-the-barcodescanner-settings-optional) - - [Customize the UI (optional)](#customize-the-ui-optional) - - [API Documentation](#api-documentation) - - [System Requirements](#system-requirements) - - [How to Upgrade](#how-to-upgrade) - - [Release Notes](#release-notes) - - [Next Steps](#next-steps) - -**Popular Examples** - -- Hello World - [Guide](#hello-world---simplest-implementation) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.2.12/1.hello-world/1.hello-world.html) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/1.hello-world.html?ver=9.2.12&utm_source=guide) -- Angular App - [Guide](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/helloworld-angular.html?ver=9.2.12&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.2.12/1.hello-world/3.read-video-angular) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/3.read-video-angular/dist/hello-world/?ver=9.2.12&utm_source=guide) -- React App - [Guide](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/helloworld-reactjs.html?ver=9.2.12&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.2.12/1.hello-world/4.read-video-react) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/4.read-video-react/build/?ver=9.2.12&utm_source=guide) -- Vue App - [Guide](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/helloworld-vuejsv3.html?ver=9.2.12&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.2.12/1.hello-world/6.read-video-vue3) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/6.read-video-vue3/dist/?ver=9.2.12&utm_source=guide) -- PWA App - [Guide](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/helloworld-pwa.html?ver=9.2.12&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.2.12/1.hello-world/10.read-video-pwa) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/10.read-video-pwa/helloworld-pwa.html?ver=9.2.12&utm_source=guide) -- Read Driver Licenses - [Guide](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/use-cases.html?ver=latest#read-the-pdf417-barcode-on-the-drivers-license?ver=9.2.12&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.2.12/4.use-case/2.read-a-drivers-license.html) \| [Run](https://demo.dynamsoft.com/samples/dbr/js/4.use-case/2.read-a-drivers-license.html?ver=9.2.12&utm_source=guide) -- Fill A Form - [Guide](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/use-cases.html?ver=latest#read-barcodes-and-fill-form-fields?ver=9.2.12&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.2.12/4.use-case/1.fill-a-form-with-barcode-reading.html) \| [Run](https://demo.dynamsoft.com/samples/dbr/js/4.use-case/1.fill-a-form-with-barcode-reading.html?ver=9.2.12&utm_source=guide) - -You can also: - -- Try the Official Demo - [Run](https://demo.dynamsoft.com/barcode-reader-js/?ver=9.2.12&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-demo/) -- Try Online Examples - [Run](https://demo.dynamsoft.com/Samples/DBR/JS/index.html?ver=9.2.12&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/v9.2.12/) - -## Hello World - Simplest Implementation - -Let's start with the "Hello World" example of the DBR-JS SDK which demonstrates how to use the minimum code to enable a web page to read barcodes from a live video stream. - -- Basic Requirements - - Internet connection - - [A supported browser](#system-requirements) - - Camera access - -### Understand the code - -The complete code of the "Hello World" example is shown below - -```html - - - - - - - - - -``` - -

- - Code in Github - -   - - Run via JSFiddle - -   - - Run in Dynamsoft - -

- ------ - -#### About the code - -- `license`: This property specifies a license key. Note that the license "DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9" used in this example is an online license and requires network connection to work. Read more on [Specify the license](#specify-the-license). - -- `createInstance()`: This method creates a `BarcodeScanner` object. This object can read barcodes directly from a video input with the help of its interactive UI (hidden by default) and the MediaDevices interface. - -- `onFrameRead`: This event is triggered every time the SDK finishes scanning a video frame. The `results` object contains all the barcode results that the SDK have found on this frame. In this example, we print the results to the browser console. - -- `onUniqueRead`: This event is triggered when the SDK finds a new barcode, which is not a duplicate among multiple frames. `txt` holds the barcode text value while `result` is an object that holds details of the barcode. In this example, an alert will be displayed for this new barcode. - -- `show()`: This method brings up the built-in UI of the `BarcodeScanner` object and starts scanning. - -### Run the example - -You can run the example deployed to the Dynamsoft Demo Server or test it with JSFiddle code editor. You will be asked to allow access to your camera, after which the video will be displayed on the page. After that, you can point the camera at a barcode to read it. - -When a barcode is decoded, you will see the result text pop up and the barcode location will be highlighted in the video feed. - -Alternatively, you can make a local test simply by taking the code in step 1, pasting it in a file with the name "hello-world.html" and open it in a browser. - -*Note*: - -If you open the web page as `file:///` or `http://` , the camera may not work correctly because the API getUserMedia usually requires HTTPS to access the camera. - -To make sure your web application can access the camera, please configure your web server to support HTTPS. The following links may help. - -1. NGINX: Configuring HTTPS servers -2. IIS: Create a Self Signed Certificate in IIS -3. Tomcat: Setting Up SSL on Tomcat in 5 minutes -4. Node.js: npm tls - -If the test doesn't go as expected, you can [contact us](https://www.dynamsoft.com/contact/?ver=9.2.12&utm_source=guide). - -## Building your own page - -### Include the SDK - -#### Use a CDN - -The simplest way to include the SDK is to use either the [jsDelivr](https://jsdelivr.com/) or [UNPKG](https://unpkg.com/) CDN. The "hello world" example above uses **jsDelivr**. - -- jsDelivr - - ```html - - ``` - -- UNPKG - - ```html - - ``` - -#### Host the SDK yourself - -Besides using the CDN, you can also download the SDK and host its files on your own website / server before including it in your application. - -Options to download the SDK: - -- From the website - - Download the JavaScript Package - -- yarn - - ```cmd - yarn add dynamsoft-javascript-barcode - ``` - -- npm - - ```cmd - npm install dynamsoft-javascript-barcode --save - ``` - -Depending on how you downloaded the SDK and how you intend to use it, you can typically include it like this: - -```html - -``` - -or - -```html - -``` - -or - -```typescript -import { BarcodeScanner } from 'dynamsoft-javascript-barcode'; -``` - -### Configure the SDK - -Before using the SDK, you need to configure a few things. - -#### Specify the license - -The SDK requires a license to work, use the API `license` to specify a license key. - -```javascript -Dynamsoft.DBR.BarcodeScanner.license = "YOUR-LICENSE-KEY"; -``` - -To test the SDK, you can request a 30-day trial license via the Request a Trial License link. - -> If you registered a Dynamsoft account and downloaded the SDK from the official website, Dynamsoft will automatically generate a 30-day trial license for you and put the license key into all the samples that come with the SDK. - -#### Specify the location of the "engine" files - -This is usually only required with frameworks like Angular or React, etc. where dbr.js is compiled into another file. - -The purpose is to tell the SDK where to find the engine files (\*.worker.js, \*.wasm.js and \*.wasm, etc.). The API is called `engineResourcePath`: - -```javascript -//The following code uses the jsDelivr CDN, feel free to change it to your own location of these files -Dynamsoft.DBR.BarcodeScanner.engineResourcePath = "https://cdn.jsdelivr.net/npm/dynamsoft-javascript-barcode@9.2.12/dist/"; -``` - -### Interact with the SDK - -#### Create a `BarcodeScanner` object - -You can use one of two classes ( `BarcodeScanner` and `BarcodeReader` ) to interact with the SDK. `BarcodeReader` is a low-level class that processes images directly. `BarcodeScanner` , on the other hand, inherits from `BarcodeReader` and provides high-level APIs and a built-in GUI to allow continuous barcode scanning on video frames. We'll focus on `BarcodeScanner` in this guide. - -To use the SDK, we first create a `BarcodeScanner` object. - -```javascript -Dynamsoft.DBR.BarcodeScanner.license = "YOUR-LICENSE-KEY"; -let scanner = null; -try { - scanner = await Dynamsoft.DBR.BarcodeScanner.createInstance(); -} catch (ex) { - console.error(ex); -} -``` - -Tip: When creating a `BarcodeScanner` object within a function which may be called more than once, it's best to use a "helper" variable to avoid double creation such as `pScanner` in the following code - -```javascript -Dynamsoft.DBR.BarcodeScanner.license = "YOUR-LICENSE-KEY"; -let pScanner = null; -document.getElementById('btn-scan').addEventListener('click', async () => { - try { - const scanner = await (pScanner = pScanner || Dynamsoft.DBR.BarcodeScanner.createInstance()); - } catch (ex) { - console.error(ex); - } -}); -``` - -#### Customize the `BarcodeScanner` Settings (optional) - -Let's take a look at the following code snippets: - -```javascript -// Sets which camera and what resolution to use -let allCameras = await scanner.getAllCameras(); -await scanner.setCurrentCamera(allCameras[0].deviceId); -await scanner.setResolution(1280, 720); -``` - -```javascript -// Sets up the scanner behavior -let scanSettings = await scanner.getScanSettings(); -// Disregards duplicated results found in a specified time period (in milliseconds). -scanSettings.duplicateForgetTime = 5000; // The default is 3000 -// Sets a scan interval in milliseconds so the SDK may release the CPU from time to time. -// (setting this value larger is a simple way to save battery power and reduce device heating). -scanSettings.intervalTime = 100; // The default is 0. -// Sets captureAndDecodeInParallel to false, which tells the SDK not to acquire the next frame while decoding the first. -// This is another way to save battery power and is recommended on low-end phones. However, it does slow down the decoding speed. -scanSettings.captureAndDecodeInParallel = false; // The default is true. -await scanner.updateScanSettings(scanSettings); -``` - -```javascript -// Uses one of the built-in RuntimeSetting templates: "single" (decode a single barcode, the default mode), "speed", "balance", "coverage", "dense" and "distance" -await scanner.updateRuntimeSettings("speed"); - -// Makes changes to the template. The code below demonstrates how to specify enabled symbologies -let runtimeSettings = await scanner.getRuntimeSettings(); -runtimeSettings.barcodeFormatIds = Dynamsoft.DBR.EnumBarcodeFormat.BF_ONED | Dynamsoft.DBR.EnumBarcodeFormat.BF_QR_CODE; -await scanner.updateRuntimeSettings(runtimeSettings); -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/yfkcajxz/) - -As you can see from the above code snippets, there are three types of configurations: - -- Customize the data source: This configuration includes which camera to use, the preferred resolution, etc. Learn more here. - -- `get/updateScanSettings`: Configures the behavior of the scanner which includes `duplicateForgetTime` and `intervalTime`, etc. - -- `get/updateRuntimeSettings`: Configures the decode engine with either a built-in template or a comprehensive `RuntimeSettings` object. For example, the following uses the built-in "speed" settings with updated `localizationModes`. - - ```javascript - await barcodeScanner.updateRuntimeSettings("speed"); - //await barcodeScanner.updateRuntimeSettings("balance"); //alternative - //await barcodeScanner.updateRuntimeSettings("coverage"); //alternative - let settings = await barcodeScanner.getRuntimeSettings(); - settings.localizationModes = [ - Dynamsoft.DBR.EnumLocalizationMode.LM_CONNECTED_BLOCKS, - Dynamsoft.DBR.EnumLocalizationMode.LM_SCAN_DIRECTLY, - Dynamsoft.DBR.EnumLocalizationMode.LM_LINES, 0, 0, 0, 0, 0 - ]; - await barcodeScanner.updateRuntimeSettings(settings); - ``` - - Try in [JSFiddle](https://jsfiddle.net/DynamsoftTeam/f24h8c1m/). - - See also [settings samples](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/parameter-settings.html?ver=9.2.12&utm_source=guide). - -> Find the full list of the runtime settings here. - -### Customize the UI (optional) - -The built-in UI of the `BarcodeScanner` object is defined in the file `dist/dbr.ui.html` . There are a few ways to customize it: - -- Modify the file `dist/dbr.ui.html` directly. - - This option is only possible when you host this file on your own web server instead of using a CDN. - -- Copy the file `dist/dbr.ui.html` to your application, modify it and use the the API `defaultUIElementURL` to set it as the default UI. - - ```javascript - // This line only takes effect when it is put before the method `createInstance()` is called. - Dynamsoft.DBR.BarcodeScanner.defaultUIElementURL = "THE-URL-TO-THE-FILE"; - ``` - -- Append the default UI element to your page, customize it before showing it. - - ```html -
- ``` - - ```javascript - document.getElementById('div-ui-container').appendChild(scanner.getUIElement()); - document.getElementsByClassName('dce-btn-close')[0].hidden = true; // Hide the close button - ``` - -- Build the UI element from scratch and connect it to the SDK with the API `setUIElement(HTMLElement)`. - - - Embed the video - - ```html -
-
-
- - ``` - - > 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` . - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/2jzeq1r6/) - - - Add the camera list and resolution list - - If the class names for these lists match the default ones, `dce-sel-camera` and `dce-sel-resolution` , the SDK will automatically populate the lists and handle the camera/resolution switching. - - ```html -
-
-
-
- ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/nbj75vxu/) - - ```html -
- - -
-
-
- ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/25v08paf/) - - > By default, only 3 hard-coded resolutions (3840 x 2160, 1920 x 1080, 1280 x 720), are populated as options. You can show a customized set of options by hardcoding them. - - ```html - - ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/tnfjks4q/) - - > Generally, you need to provide a resolution that the camera supports. However, in case a camera does not support the specified resolution, it usually uses the cloest supported resolution. As a result, the selected resolution may not be the actual resolution. In this case, add an option with the class name `dce-opt-gotResolution` (as shown above) and the SDK will then use it to show the **actual resolution**. - - See also [UI customization samples](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/ui-customization.html?ver=9.2.12&utm_source=guide). - -## API Documentation - -You can check out the detailed documentation about the APIs of the SDK at -[https://www.dynamsoft.com/barcode-reader/programming/javascript/api-reference/?ver=9.2.12](https://www.dynamsoft.com/barcode-reader/programming/javascript/api-reference/?ver=9.2.12). - -## System Requirements - -DBR requires the following features to work: - -- Secure context (HTTPS deployment) - - When deploying your application / website for production, make sure to serve it via a secure HTTPS connection. This is required for two reasons - - - Access to the camera video stream is only granted in a security context. Most browsers impose this restriction. - > Some browsers like Chrome may grant the access for `http://127.0.0.1` and `http://localhost` or even for pages opened directly from the local disk (`file:///...`). This can be helpful for temporary development and test. - - - Dynamsoft License requires a secure context to work. - -- `WebAssembly`, `Blob`, `URL`/`createObjectURL`, `Web Workers` - - The above four features are required for the SDK to work. - -- `MediaDevices`/`getUserMedia` - - This API is only required for in-browser video streaming. If a browser does not support this API, the [Single Frame Mode](https://www.dynamsoft.com/barcode-reader/programming/javascript/api-reference/BarcodeScanner.html?ver=9.2.12&utm_source=guide#singleframemode) will be used automatically. If the API exists but doesn't work correctly, the Single Frame Mode can be used as an alternative way to access the camera. - -- `getSettings` - - This API inspects the video input which is a `MediaStreamTrack` object about its constrainable properties. - -The following table is a list of supported browsers based on the above requirements: - - Browser Name | Version - :-: | :-: - Chrome | v59+1 - Firefox | v52+ (v55+ on Android/iOS1) - Edge2 | v16+ - Safari3 | v11+ - - 1 iOS 14.3+ is required for camera video streaming in Chrome and Firefox or Apps using webviews. - - 2 On Edge, due to strict Same-origin policy, you must host the SDK files on the same domain as your web page. - - 3 Safari v11.x already has the required features, but it has many other issues, so we recommend v12+. - -Apart from the browsers, the operating systems may impose some limitations of their own that could restrict the use of the SDK. Browser compatibility ultimately depends on whether the browser on that particular operating system supports the features listed above. - -## How to Upgrade - -If you want to upgrade the SDK from an old version to a newer one, please see [how to upgrade](https://www.dynamsoft.com/barcode-reader/programming/javascript/upgrade-guide/?ver=9.2.12&utm_source=guide). - -## Release Notes - -Learn about what are included in each release at [https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/release-notes/?ver=latest](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/release-notes/?ver=latest). - -## Next Steps - -Now that you have got the SDK integrated, you can choose to move forward in the following directions - -1. Check out the [Official Samples and Demo](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/index.html?ver=latest) -2. Learn how to make use of the [SDK features](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/user-guide/explore-features/index.html?ver=latest) -3. See how the SDK works in [Popular Use Cases](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/user-guide/use-cases/index.html?ver=latest) diff --git a/programming-old/javascript/user-guide/index-v9.2.13.md b/programming-old/javascript/user-guide/index-v9.2.13.md deleted file mode 100644 index fc074aab..00000000 --- a/programming-old/javascript/user-guide/index-v9.2.13.md +++ /dev/null @@ -1,492 +0,0 @@ ---- -layout: default-layout -title: v9.2.13 User Guide - Dynamsoft Barcode Reader JavaScript Edition -description: This is the user guide of Dynamsoft Barcode Reader JavaScript SDK. -keywords: user guide, javascript, js -breadcrumbText: User Guide -noTitleIndex: true -needGenerateH3Content: true -needAutoGenerateSidebar: true -permalink: /programming/javascript/user-guide/index-v9.2.13.html ---- - - - -# Barcode Reader for Your Website - User Guide - -[Dynamsoft Barcode Reader JavaScript Edition](https://www.dynamsoft.com/barcode-reader/sdk-javascript/) (DBR-JS) is equipped with industry-leading algorithms for exceptional speed, accuracy and read rates in barcode reading. Using its well-designed API, you can turn your web page into a barcode scanner with just a few lines of code. - -![version](https://img.shields.io/npm/v/dynamsoft-javascript-barcode.svg) -![downloads](https://img.shields.io/npm/dm/dynamsoft-javascript-barcode.svg) -![jsdelivr](https://img.shields.io/jsdelivr/npm/hm/dynamsoft-javascript-barcode.svg) -![vulnerabilities](https://img.shields.io/snyk/vulnerabilities/npm/dynamsoft-javascript-barcode.svg) - -Once the DBR-JS SDK gets integrated into your web page, your users can access a camera via the browser and read barcodes directly from its video input. - -In this guide, you will learn step by step on how to integrate the DBR-JS SDK into your website. - -Table of Contents - -- [Barcode Reader for Your Website - User Guide](#barcode-reader-for-your-website---user-guide) - - [Hello World - Simplest Implementation](#hello-world---simplest-implementation) - - [Understand the code](#understand-the-code) - - [About the code](#about-the-code) - - [Run the example](#run-the-example) - - [Building your own page](#building-your-own-page) - - [Include the SDK](#include-the-sdk) - - [Use a CDN](#use-a-cdn) - - [Host the SDK yourself](#host-the-sdk-yourself) - - [Configure the SDK](#configure-the-sdk) - - [Specify the license](#specify-the-license) - - [Specify the location of the "engine" files](#specify-the-location-of-the-engine-files) - - [Interact with the SDK](#interact-with-the-sdk) - - [Create a `BarcodeScanner` object](#create-a-barcodescanner-object) - - [Customize the `BarcodeScanner` Settings (optional)](#customize-the-barcodescanner-settings-optional) - - [Customize the UI (optional)](#customize-the-ui-optional) - - [API Documentation](#api-documentation) - - [System Requirements](#system-requirements) - - [How to Upgrade](#how-to-upgrade) - - [Release Notes](#release-notes) - - [Next Steps](#next-steps) - -**Popular Examples** - -- Hello World - [Guide](#hello-world---simplest-implementation) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.2.13/1.hello-world/1.hello-world.html) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/1.hello-world.html?ver=9.2.13&utm_source=guide) -- Angular App - [Guide](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/helloworld-angular.html?ver=9.2.13&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.2.13/1.hello-world/3.read-video-angular) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/3.read-video-angular/dist/hello-world/?ver=9.2.13&utm_source=guide) -- React App - [Guide](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/helloworld-reactjs.html?ver=9.2.13&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.2.13/1.hello-world/4.read-video-react) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/4.read-video-react/build/?ver=9.2.13&utm_source=guide) -- Vue App - [Guide](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/helloworld-vuejsv3.html?ver=9.2.13&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.2.13/1.hello-world/6.read-video-vue3) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/6.read-video-vue3/dist/?ver=9.2.13&utm_source=guide) -- PWA App - [Guide](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/helloworld-pwa.html?ver=9.2.13&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.2.13/1.hello-world/10.read-video-pwa) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/10.read-video-pwa/helloworld-pwa.html?ver=9.2.13&utm_source=guide) -- Read Driver Licenses - [Guide](https://www.dynamsoft.com/barcode-reader/docs/core/programming/usecases/scan-and-parse-AAMVA.html?ver=9.2.13&utm_source=guide&&lang=js) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.2.13/4.use-case/2.read-a-drivers-license.html) \| [Run](https://demo.dynamsoft.com/samples/dbr/js/4.use-case/2.read-a-drivers-license.html?ver=9.2.13&utm_source=guide) -- Fill A Form - [Guide](https://www.dynamsoft.com/barcode-reader/docs/core/programming/usecases/scan-barcodes-as-input.html?lang=js&&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.2.13/4.use-case/1.fill-a-form-with-barcode-reading.html) \| [Run](https://demo.dynamsoft.com/samples/dbr/js/4.use-case/1.fill-a-form-with-barcode-reading.html?ver=9.2.13&utm_source=guide) - -You can also: - -- Try the Official Demo - [Run](https://demo.dynamsoft.com/barcode-reader-js/?ver=9.2.13&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-demo/) -- Try Online Examples - [Run](https://demo.dynamsoft.com/Samples/DBR/JS/index.html?ver=9.2.13&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/v9.2.13/) - -## Hello World - Simplest Implementation - -Let's start with the "Hello World" example of the DBR-JS SDK which demonstrates how to use the minimum code to enable a web page to read barcodes from a live video stream. - -- Basic Requirements - - Internet connection - - [A supported browser](#system-requirements) - - Camera access - -### Understand the code - -The complete code of the "Hello World" example is shown below - -```html - - - - - - - - - -``` - -

- - Code in Github - -   - - Run via JSFiddle - -   - - Run in Dynamsoft - -

- ------ - -#### About the code - -- `license`: This property specifies a license key. Note that the license "DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9" used in this example is an online license and requires network connection to work. Read more on [Specify the license](#specify-the-license). - -- `createInstance()`: This method creates a `BarcodeScanner` object. This object can read barcodes directly from a video input with the help of its interactive UI (hidden by default) and the MediaDevices interface. - -- `onFrameRead`: This event is triggered every time the SDK finishes scanning a video frame. The `results` object contains all the barcode results that the SDK have found on this frame. In this example, we print the results to the browser console. - -- `onUniqueRead`: This event is triggered when the SDK finds a new barcode, which is not a duplicate among multiple frames. `txt` holds the barcode text value while `result` is an object that holds details of the barcode. In this example, an alert will be displayed for this new barcode. - -- `show()`: This method brings up the built-in UI of the `BarcodeScanner` object and starts scanning. - -### Run the example - -You can run the example deployed to the Dynamsoft Demo Server or test it with JSFiddle code editor. You will be asked to allow access to your camera, after which the video will be displayed on the page. After that, you can point the camera at a barcode to read it. - -When a barcode is decoded, you will see the result text pop up and the barcode location will be highlighted in the video feed. - -Alternatively, you can make a local test simply by taking the code in step 1, pasting it in a file with the name "hello-world.html" and open it in a browser. - -*Note*: - -If you open the web page as `file:///` or `http://` , the camera may not work correctly because the API getUserMedia usually requires HTTPS to access the camera. - -To make sure your web application can access the camera, please configure your web server to support HTTPS. The following links may help. - -1. NGINX: Configuring HTTPS servers -2. IIS: Create a Self Signed Certificate in IIS -3. Tomcat: Setting Up SSL on Tomcat in 5 minutes -4. Node.js: npm tls - -If the test doesn't go as expected, you can [contact us](https://www.dynamsoft.com/contact/?ver=9.2.13&utm_source=guide). - -## Building your own page - -### Include the SDK - -#### Use a CDN - -The simplest way to include the SDK is to use either the [jsDelivr](https://jsdelivr.com/) or [UNPKG](https://unpkg.com/) CDN. The "hello world" example above uses **jsDelivr**. - -- jsDelivr - - ```html - - ``` - -- UNPKG - - ```html - - ``` - -#### Host the SDK yourself - -Besides using the CDN, you can also download the SDK and host its files on your own website / server before including it in your application. - -Options to download the SDK: - -- From the website - - Download the JavaScript Package - -- yarn - - ```cmd - yarn add dynamsoft-javascript-barcode - ``` - -- npm - - ```cmd - npm install dynamsoft-javascript-barcode --save - ``` - -Depending on how you downloaded the SDK and how you intend to use it, you can typically include it like this: - -```html - -``` - -or - -```html - -``` - -or - -```typescript -import { BarcodeScanner } from 'dynamsoft-javascript-barcode'; -``` - -### Configure the SDK - -Before using the SDK, you need to configure a few things. - -#### Specify the license - -The SDK requires a license to work, use the API `license` to specify a license key. - -```javascript -Dynamsoft.DBR.BarcodeScanner.license = "YOUR-LICENSE-KEY"; -``` - -To test the SDK, you can request a 30-day trial license via the Request a Trial License link. - -> If you registered a Dynamsoft account and downloaded the SDK from the official website, Dynamsoft will automatically generate a 30-day trial license for you and put the license key into all the samples that come with the SDK. - -#### Specify the location of the "engine" files - -This is usually only required with frameworks like Angular or React, etc. where dbr.js is compiled into another file. - -The purpose is to tell the SDK where to find the engine files (\*.worker.js, \*.wasm.js and \*.wasm, etc.). The API is called `engineResourcePath`: - -```javascript -//The following code uses the jsDelivr CDN, feel free to change it to your own location of these files -Dynamsoft.DBR.BarcodeScanner.engineResourcePath = "https://cdn.jsdelivr.net/npm/dynamsoft-javascript-barcode@9.2.13/dist/"; -``` - -### Interact with the SDK - -#### Create a `BarcodeScanner` object - -You can use one of two classes ( `BarcodeScanner` and `BarcodeReader` ) to interact with the SDK. `BarcodeReader` is a low-level class that processes images directly. `BarcodeScanner` , on the other hand, inherits from `BarcodeReader` and provides high-level APIs and a built-in GUI to allow continuous barcode scanning on video frames. We'll focus on `BarcodeScanner` in this guide. - -To use the SDK, we first create a `BarcodeScanner` object. - -```javascript -Dynamsoft.DBR.BarcodeScanner.license = "YOUR-LICENSE-KEY"; -let scanner = null; -try { - scanner = await Dynamsoft.DBR.BarcodeScanner.createInstance(); -} catch (ex) { - console.error(ex); -} -``` - -Tip: When creating a `BarcodeScanner` object within a function which may be called more than once, it's best to use a "helper" variable to avoid double creation such as `pScanner` in the following code - -```javascript -Dynamsoft.DBR.BarcodeScanner.license = "YOUR-LICENSE-KEY"; -let pScanner = null; -document.getElementById('btn-scan').addEventListener('click', async () => { - try { - const scanner = await (pScanner = pScanner || Dynamsoft.DBR.BarcodeScanner.createInstance()); - } catch (ex) { - console.error(ex); - } -}); -``` - -#### Customize the `BarcodeScanner` Settings (optional) - -Let's take a look at the following code snippets: - -```javascript -// Sets which camera and what resolution to use -let allCameras = await scanner.getAllCameras(); -await scanner.setCurrentCamera(allCameras[0].deviceId); -await scanner.setResolution(1280, 720); -``` - -```javascript -// Sets up the scanner behavior -let scanSettings = await scanner.getScanSettings(); -// Disregards duplicated results found in a specified time period (in milliseconds). -scanSettings.duplicateForgetTime = 5000; // The default is 3000 -// Sets a scan interval in milliseconds so the SDK may release the CPU from time to time. -// (setting this value larger is a simple way to save battery power and reduce device heating). -scanSettings.intervalTime = 100; // The default is 0. -// Sets captureAndDecodeInParallel to false, which tells the SDK not to acquire the next frame while decoding the first. -// This is another way to save battery power and is recommended on low-end phones. However, it does slow down the decoding speed. -scanSettings.captureAndDecodeInParallel = false; // The default is true. -await scanner.updateScanSettings(scanSettings); -``` - -```javascript -// Uses one of the built-in RuntimeSetting templates: "single" (decode a single barcode, the default mode), "speed", "balance", "coverage", "dense" and "distance" -await scanner.updateRuntimeSettings("speed"); - -// Makes changes to the template. The code below demonstrates how to specify enabled symbologies -let runtimeSettings = await scanner.getRuntimeSettings(); -runtimeSettings.barcodeFormatIds = Dynamsoft.DBR.EnumBarcodeFormat.BF_ONED | Dynamsoft.DBR.EnumBarcodeFormat.BF_QR_CODE; -await scanner.updateRuntimeSettings(runtimeSettings); -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/yfkcajxz/) - -As you can see from the above code snippets, there are three types of configurations: - -- Customize the data source: This configuration includes which camera to use, the preferred resolution, etc. Learn more here. - -- `get/updateScanSettings`: Configures the behavior of the scanner which includes `duplicateForgetTime` and `intervalTime`, etc. - -- `get/updateRuntimeSettings`: Configures the decode engine with either a built-in template or a comprehensive `RuntimeSettings` object. For example, the following uses the built-in "speed" settings with updated `localizationModes`. - - ```javascript - await barcodeScanner.updateRuntimeSettings("speed"); - //await barcodeScanner.updateRuntimeSettings("balance"); //alternative - //await barcodeScanner.updateRuntimeSettings("coverage"); //alternative - let settings = await barcodeScanner.getRuntimeSettings(); - settings.localizationModes = [ - Dynamsoft.DBR.EnumLocalizationMode.LM_CONNECTED_BLOCKS, - Dynamsoft.DBR.EnumLocalizationMode.LM_SCAN_DIRECTLY, - Dynamsoft.DBR.EnumLocalizationMode.LM_LINES, 0, 0, 0, 0, 0 - ]; - await barcodeScanner.updateRuntimeSettings(settings); - ``` - - Try in [JSFiddle](https://jsfiddle.net/DynamsoftTeam/f24h8c1m/). - - See also [settings samples](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/parameter-settings.html?ver=9.2.13&utm_source=guide). - -> Find the full list of the runtime settings here. - -### Customize the UI (optional) - -The built-in UI of the `BarcodeScanner` object is defined in the file `dist/dbr.ui.html` . There are a few ways to customize it: - -- Modify the file `dist/dbr.ui.html` directly. - - This option is only possible when you host this file on your own web server instead of using a CDN. - -- Copy the file `dist/dbr.ui.html` to your application, modify it and use the the API `defaultUIElementURL` to set it as the default UI. - - ```javascript - // This line only takes effect when it is put before the method `createInstance()` is called. - Dynamsoft.DBR.BarcodeScanner.defaultUIElementURL = "THE-URL-TO-THE-FILE"; - ``` - -- Append the default UI element to your page, customize it before showing it. - - ```html -
- ``` - - ```javascript - document.getElementById('div-ui-container').appendChild(scanner.getUIElement()); - document.getElementsByClassName('dce-btn-close')[0].hidden = true; // Hide the close button - ``` - -- Build the UI element from scratch and connect it to the SDK with the API `setUIElement(HTMLElement)`. - - - Embed the video - - ```html -
-
-
- - ``` - - > 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` . - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/2jzeq1r6/) - - - Add the camera list and resolution list - - If the class names for these lists match the default ones, `dce-sel-camera` and `dce-sel-resolution` , the SDK will automatically populate the lists and handle the camera/resolution switching. - - ```html -
-
-
-
- ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/nbj75vxu/) - - ```html -
- - -
-
-
- ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/25v08paf/) - - > By default, only 3 hard-coded resolutions (3840 x 2160, 1920 x 1080, 1280 x 720), are populated as options. You can show a customized set of options by hardcoding them. - - ```html - - ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/tnfjks4q/) - - > Generally, you need to provide a resolution that the camera supports. However, in case a camera does not support the specified resolution, it usually uses the cloest supported resolution. As a result, the selected resolution may not be the actual resolution. In this case, add an option with the class name `dce-opt-gotResolution` (as shown above) and the SDK will then use it to show the **actual resolution**. - - See also [UI customization samples](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/ui-customization.html?ver=9.2.13&utm_source=guide). - -## API Documentation - -You can check out the detailed documentation about the APIs of the SDK at -[https://www.dynamsoft.com/barcode-reader/programming/javascript/api-reference/?ver=9.2.13](https://www.dynamsoft.com/barcode-reader/programming/javascript/api-reference/?ver=9.2.13). - -## System Requirements - -DBR requires the following features to work: - -- Secure context (HTTPS deployment) - - When deploying your application / website for production, make sure to serve it via a secure HTTPS connection. This is required for two reasons - - - Access to the camera video stream is only granted in a security context. Most browsers impose this restriction. - > Some browsers like Chrome may grant the access for `http://127.0.0.1` and `http://localhost` or even for pages opened directly from the local disk (`file:///...`). This can be helpful for temporary development and test. - - - Dynamsoft License requires a secure context to work. - -- `WebAssembly`, `Blob`, `URL`/`createObjectURL`, `Web Workers` - - The above four features are required for the SDK to work. - -- `MediaDevices`/`getUserMedia` - - This API is only required for in-browser video streaming. If a browser does not support this API, the [Single Frame Mode](https://www.dynamsoft.com/barcode-reader/programming/javascript/api-reference/BarcodeScanner.html?ver=9.2.13&utm_source=guide#singleframemode) will be used automatically. If the API exists but doesn't work correctly, the Single Frame Mode can be used as an alternative way to access the camera. - -- `getSettings` - - This API inspects the video input which is a `MediaStreamTrack` object about its constrainable properties. - -The following table is a list of supported browsers based on the above requirements: - - Browser Name | Version - :-: | :-: - Chrome | v59+1 - Firefox | v52+ (v55+ on Android/iOS1) - Edge2 | v16+ - Safari3 | v11+ - - 1 iOS 14.3+ is required for camera video streaming in Chrome and Firefox or Apps using webviews. - - 2 On Edge, due to strict Same-origin policy, you must host the SDK files on the same domain as your web page. - - 3 Safari v11.x already has the required features, but it has many other issues, so we recommend v12+. - -Apart from the browsers, the operating systems may impose some limitations of their own that could restrict the use of the SDK. Browser compatibility ultimately depends on whether the browser on that particular operating system supports the features listed above. - -## How to Upgrade - -If you want to upgrade the SDK from an old version to a newer one, please see [how to upgrade](https://www.dynamsoft.com/barcode-reader/programming/javascript/upgrade-guide/?ver=9.2.13&utm_source=guide). - -## Release Notes - -Learn about what are included in each release at [https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/release-notes/?ver=latest](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/release-notes/?ver=latest). - -## Next Steps - -Now that you have got the SDK integrated, you can choose to move forward in the following directions - -1. Check out the [Official Samples and Demo](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/index.html?ver=latest) -2. Learn how to make use of the [SDK features](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/user-guide/explore-features/index.html?ver=latest) -3. See how the SDK works in [Popular Use Cases](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/user-guide/use-cases/index.html?ver=latest) diff --git a/programming-old/javascript/user-guide/index-v9.3.1.md b/programming-old/javascript/user-guide/index-v9.3.1.md deleted file mode 100644 index 998fe063..00000000 --- a/programming-old/javascript/user-guide/index-v9.3.1.md +++ /dev/null @@ -1,508 +0,0 @@ ---- -layout: default-layout -title: v9.3.1 User Guide - Dynamsoft Barcode Reader JavaScript Edition -description: This is the user guide of Dynamsoft Barcode Reader JavaScript SDK. -keywords: user guide, javascript, js -breadcrumbText: User Guide -noTitleIndex: true -needGenerateH3Content: true -needAutoGenerateSidebar: true -permalink: /programming/javascript/user-guide/index-v9.3.1.html ---- - - - -# Barcode Reader for Your Website - User Guide - -[Dynamsoft Barcode Reader JavaScript Edition](https://www.dynamsoft.com/barcode-reader/sdk-javascript/) (DBR-JS) is equipped with industry-leading algorithms for exceptional speed, accuracy and read rates in barcode reading. Using its well-designed API, you can turn your web page into a barcode scanner with just a few lines of code. - -![version](https://img.shields.io/npm/v/dynamsoft-javascript-barcode.svg) -![downloads](https://img.shields.io/npm/dm/dynamsoft-javascript-barcode.svg) -![jsdelivr](https://img.shields.io/jsdelivr/npm/hm/dynamsoft-javascript-barcode.svg) -![vulnerabilities](https://img.shields.io/snyk/vulnerabilities/npm/dynamsoft-javascript-barcode.svg) - -Once the DBR-JS SDK gets integrated into your web page, your users can access a camera via the browser and read barcodes directly from its video input. - -In this guide, you will learn step by step on how to integrate the DBR-JS SDK into your website. - -Table of Contents - -- [Barcode Reader for Your Website - User Guide](#barcode-reader-for-your-website---user-guide) - - [Hello World - Simplest Implementation](#hello-world---simplest-implementation) - - [Understand the code](#understand-the-code) - - [About the code](#about-the-code) - - [Run the example](#run-the-example) - - [Building your own page](#building-your-own-page) - - [Include the SDK](#include-the-sdk) - - [Use a public CDN](#use-a-public-cdn) - - [Host the SDK yourself](#host-the-sdk-yourself) - - [Configure the SDK](#configure-the-sdk) - - [Specify the license](#specify-the-license) - - [Specify the location of the "engine" files](#specify-the-location-of-the-engine-files) - - [Interact with the SDK](#interact-with-the-sdk) - - [Create a `BarcodeScanner` object](#create-a-barcodescanner-object) - - [Customize the `BarcodeScanner` Settings (optional)](#customize-the-barcodescanner-settings-optional) - - [Customize the UI (optional)](#customize-the-ui-optional) - - [API Documentation](#api-documentation) - - [System Requirements](#system-requirements) - - [How to Upgrade](#how-to-upgrade) - - [Release Notes](#release-notes) - - [Next Steps](#next-steps) - -**Popular Examples** - -- Hello World - [Guide](#hello-world---simplest-implementation) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.3.1/1.hello-world/1.hello-world.html) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/1.hello-world.html?ver=9.3.1&utm_source=guide) -- Angular App - [Guide](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/helloworld-angular.html?ver=9.3.1&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.3.1/1.hello-world/3.read-video-angular) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/3.read-video-angular/dist/hello-world/?ver=9.3.1&utm_source=guide) -- React App - [Guide](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/helloworld-reactjs.html?ver=9.3.1&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.3.1/1.hello-world/4.read-video-react) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/4.read-video-react/build/?ver=9.3.1&utm_source=guide) -- Vue App - [Guide](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/helloworld-vuejsv3.html?ver=9.3.1&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.3.1/1.hello-world/6.read-video-vue3) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/6.read-video-vue3/dist/?ver=9.3.1&utm_source=guide) -- PWA App - [Guide](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/helloworld-pwa.html?ver=9.3.1&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.3.1/1.hello-world/10.read-video-pwa) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/10.read-video-pwa/helloworld-pwa.html?ver=9.3.1&utm_source=guide) -- Read Driver Licenses - [Guide](https://www.dynamsoft.com/barcode-reader/docs/core/programming/usecases/scan-and-parse-AAMVA.html?ver=9.3.1&utm_source=guide&&lang=js) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.3.1/4.use-case/2.read-a-drivers-license.html) \| [Run](https://demo.dynamsoft.com/samples/dbr/js/4.use-case/2.read-a-drivers-license.html?ver=9.3.1&utm_source=guide) -- Fill A Form - [Guide](https://www.dynamsoft.com/barcode-reader/docs/core/programming/usecases/scan-barcodes-as-input.html?lang=js&&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.3.1/4.use-case/1.fill-a-form-with-barcode-reading.html) \| [Run](https://demo.dynamsoft.com/samples/dbr/js/4.use-case/1.fill-a-form-with-barcode-reading.html?ver=9.3.1&utm_source=guide) - -You can also: - -- Try the Official Demo - [Run](https://demo.dynamsoft.com/barcode-reader-js/?ver=9.3.1&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-demo/) -- Try Online Examples - [Run](https://demo.dynamsoft.com/Samples/DBR/JS/index.html?ver=9.3.1&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/v9.3.1/) - -## Hello World - Simplest Implementation - -Let's start with the "Hello World" example of the DBR-JS SDK which demonstrates how to use the minimum code to enable a web page to read barcodes from a live video stream. - -- Basic Requirements - - Internet connection - - [A supported browser](#system-requirements) - - Camera access - -### Understand the code - -The complete code of the "Hello World" example is shown below - -```html - - - - - - - - - -``` - -

- - Code in Github - -   - - Run via JSFiddle - -   - - Run in Dynamsoft - -

- ------ - -#### About the code - -- The DBR-JS SDK is included in the code via the **jsDelivr** CDN. - -> In some rare cases, you might not be able to access the CDN. If this happens, you can use (https://download2.dynamsoft.com/dbr/dynamsoft-barcode-reader-js/dynamsoft-barcode-reader-js-9.3.1/dist/dbr.js)[https://download2.dynamsoft.com/dbr/dynamsoft-barcode-reader-js/dynamsoft-barcode-reader-js-9.3.1/dist/dbr.js] for the test. However, please remember this link is temporary and DO NOT use it in your production application. Instead, you can try [hosting the SDK yourself](#host-the-sdk-yourself). - -- `license`: This property specifies a license key. Note that the license "DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9" used in this example is an online license and requires network connection to work. Read more on [Specify the license](#specify-the-license). - -- `createInstance()`: This method creates a `BarcodeScanner` object. This object can read barcodes directly from a video input with the help of its interactive UI (hidden by default) and the MediaDevices interface. - -- `onFrameRead`: This event is triggered every time the SDK finishes scanning a video frame. The `results` object contains all the barcode results that the SDK have found on this frame. In this example, we print the results to the browser console. - -- `onUniqueRead`: This event is triggered when the SDK finds a new barcode, which is not a duplicate among multiple frames. `txt` holds the barcode text value while `result` is an object that holds details of the barcode. In this example, an alert will be displayed for this new barcode. - -- `show()`: This method brings up the built-in UI of the `BarcodeScanner` object and starts scanning. - -### Run the example - -You can run the example deployed to the Dynamsoft Demo Server or test it with JSFiddle code editor. You will be asked to allow access to your camera, after which the video will be displayed on the page. After that, you can point the camera at a barcode to read it. - -When a barcode is decoded, you will see the result text pop up and the barcode location will be highlighted in the video feed. - -Alternatively, you can make a local test simply by taking the code in step 1, pasting it in a file with the name "hello-world.html" and open it in a browser. - -*Note*: - -If you open the web page as `file:///` or `http://` , the camera may not work correctly because the API getUserMedia usually requires HTTPS to access the camera. - -To make sure your web application can access the camera, please configure your web server to support HTTPS. The following links may help. - -1. NGINX: Configuring HTTPS servers -2. IIS: Create a Self Signed Certificate in IIS -3. Tomcat: Setting Up SSL on Tomcat in 5 minutes -4. Node.js: npm tls - -If the test doesn't go as expected, you can [contact us](https://www.dynamsoft.com/contact/?ver=9.3.1&utm_source=guide). - - - -## Building your own page - -### Include the SDK - -#### Use a public CDN - -The simplest way to include the SDK is to use either the [jsDelivr](https://jsdelivr.com/) or [UNPKG](https://unpkg.com/) CDN. The "hello world" example above uses **jsDelivr**. - -- jsDelivr - - ```html - - ``` - -- UNPKG - - ```html - - ``` - -#### Host the SDK yourself - -Besides using the public CDN, you can also download the SDK and host its files on your own server or a commercial CDN before including it in your application. - -Options to download the SDK: - -- From the website - - Download the JavaScript Package - -- yarn - - ```cmd - yarn add dynamsoft-javascript-barcode - ``` - -- npm - - ```cmd - npm install dynamsoft-javascript-barcode --save - ``` - -Depending on how you downloaded the SDK and how you intend to use it, you can typically include it like this: - -```html - -``` - -or - -```html - -``` - -or - -```typescript -import { BarcodeScanner } from 'dynamsoft-javascript-barcode'; -``` - -**NOTE** - -To work properly, the SDK requires a few engine files, which are relatively large and may take quite a few seconds to download. We recommend that you set a longer cache time to maximize the performance of your web application. - -```cmd -Cache-Control: max-age=31536000 -``` - -Reference: [Cache-Control](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control). - -### Configure the SDK - -Before using the SDK, you need to configure a few things. - -#### Specify the license - -The SDK requires a license to work, use the API `license` to specify a license key. - -```javascript -Dynamsoft.DBR.BarcodeScanner.license = "YOUR-LICENSE-KEY"; -``` - -To test the SDK, you can request a 30-day trial license via the Request a Trial License link. - -> If you registered a Dynamsoft account and downloaded the SDK from the official website, Dynamsoft will automatically generate a 30-day trial license for you and put the license key into all the samples that come with the SDK. - -#### Specify the location of the "engine" files - -This is usually only required with frameworks like Angular or React, etc. where dbr.js is compiled into another file. - -The purpose is to tell the SDK where to find the engine files (\*.worker.js, \*.wasm.js and \*.wasm, etc.). The API is called `engineResourcePath`: - -```javascript -//The following code uses the jsDelivr CDN, feel free to change it to your own location of these files -Dynamsoft.DBR.BarcodeScanner.engineResourcePath = "https://cdn.jsdelivr.net/npm/dynamsoft-javascript-barcode@9.3.1/dist/"; -``` - -### Interact with the SDK - -#### Create a `BarcodeScanner` object - -You can use one of two classes ( `BarcodeScanner` and `BarcodeReader` ) to interact with the SDK. `BarcodeReader` is a low-level class that processes images directly. `BarcodeScanner` , on the other hand, inherits from `BarcodeReader` and provides high-level APIs and a built-in GUI to allow continuous barcode scanning on video frames. We'll focus on `BarcodeScanner` in this guide. - -To use the SDK, we first create a `BarcodeScanner` object. - -```javascript -Dynamsoft.DBR.BarcodeScanner.license = "YOUR-LICENSE-KEY"; -let scanner = null; -try { - scanner = await Dynamsoft.DBR.BarcodeScanner.createInstance(); -} catch (ex) { - console.error(ex); -} -``` - -Tip: When creating a `BarcodeScanner` object within a function which may be called more than once, it's best to use a "helper" variable to avoid double creation such as `pScanner` in the following code - -```javascript -Dynamsoft.DBR.BarcodeScanner.license = "YOUR-LICENSE-KEY"; -let pScanner = null; -document.getElementById('btn-scan').addEventListener('click', async () => { - try { - const scanner = await (pScanner = pScanner || Dynamsoft.DBR.BarcodeScanner.createInstance()); - } catch (ex) { - console.error(ex); - } -}); -``` - -#### Customize the `BarcodeScanner` Settings (optional) - -Let's take a look at the following code snippets: - -```javascript -// Sets which camera and what resolution to use -let allCameras = await scanner.getAllCameras(); -await scanner.setCurrentCamera(allCameras[0].deviceId); -await scanner.setResolution(1280, 720); -``` - -```javascript -// Sets up the scanner behavior -let scanSettings = await scanner.getScanSettings(); -// Disregards duplicated results found in a specified time period (in milliseconds). -scanSettings.duplicateForgetTime = 5000; // The default is 3000 -// Sets a scan interval in milliseconds so the SDK may release the CPU from time to time. -// (setting this value larger is a simple way to save battery power and reduce device heating). -scanSettings.intervalTime = 100; // The default is 0. -// Sets captureAndDecodeInParallel to false, which tells the SDK not to acquire the next frame while decoding the first. -// This is another way to save battery power and is recommended on low-end phones. However, it does slow down the decoding speed. -scanSettings.captureAndDecodeInParallel = false; // The default is true. -await scanner.updateScanSettings(scanSettings); -``` - -```javascript -// Uses one of the built-in RuntimeSetting templates: "single" (decode a single barcode, the default mode), "speed", "balance", "coverage", "dense" and "distance" -await scanner.updateRuntimeSettings("speed"); - -// Makes changes to the template. The code below demonstrates how to specify enabled symbologies -let runtimeSettings = await scanner.getRuntimeSettings(); -runtimeSettings.barcodeFormatIds = Dynamsoft.DBR.EnumBarcodeFormat.BF_ONED | Dynamsoft.DBR.EnumBarcodeFormat.BF_QR_CODE; -await scanner.updateRuntimeSettings(runtimeSettings); -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/yfkcajxz/) - -As you can see from the above code snippets, there are three types of configurations: - -- Customize the data source: This configuration includes which camera to use, the preferred resolution, etc. Learn more here. - -- `get/updateScanSettings`: Configures the behavior of the scanner which includes `duplicateForgetTime` and `intervalTime`, etc. - -- `get/updateRuntimeSettings`: Configures the decode engine with either a built-in template or a comprehensive `RuntimeSettings` object. For example, the following uses the built-in "speed" settings with updated `localizationModes`. - - ```javascript - await barcodeScanner.updateRuntimeSettings("speed"); - //await barcodeScanner.updateRuntimeSettings("balance"); //alternative - //await barcodeScanner.updateRuntimeSettings("coverage"); //alternative - let settings = await barcodeScanner.getRuntimeSettings(); - settings.localizationModes = [ - Dynamsoft.DBR.EnumLocalizationMode.LM_CONNECTED_BLOCKS, - Dynamsoft.DBR.EnumLocalizationMode.LM_SCAN_DIRECTLY, - Dynamsoft.DBR.EnumLocalizationMode.LM_LINES, 0, 0, 0, 0, 0 - ]; - await barcodeScanner.updateRuntimeSettings(settings); - ``` - - Try in [JSFiddle](https://jsfiddle.net/DynamsoftTeam/f24h8c1m/). - - See also [settings samples](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/parameter-settings.html?ver=9.3.1&utm_source=guide). - -> Find the full list of the runtime settings here. - -### Customize the UI (optional) - -The built-in UI of the `BarcodeScanner` object is defined in the file `dist/dbr.ui.html` . There are a few ways to customize it: - -- Modify the file `dist/dbr.ui.html` directly. - - This option is only possible when you host this file on your own web server instead of using a CDN. - -- Copy the file `dist/dbr.ui.html` to your application, modify it and use the the API `defaultUIElementURL` to set it as the default UI. - - ```javascript - // This line only takes effect when it is put before the method `createInstance()` is called. - Dynamsoft.DBR.BarcodeScanner.defaultUIElementURL = "THE-URL-TO-THE-FILE"; - ``` - -- Append the default UI element to your page, customize it before showing it. - - ```html -
- ``` - - ```javascript - document.getElementById('div-ui-container').appendChild(scanner.getUIElement()); - document.getElementsByClassName('dce-btn-close')[0].hidden = true; // Hide the close button - ``` - -- Build the UI element from scratch and connect it to the SDK with the API `setUIElement(HTMLElement)`. - - - Embed the video - - ```html -
-
-
- - ``` - - > 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` . - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/2jzeq1r6/) - - - Add the camera list and resolution list - - If the class names for these lists match the default ones, `dce-sel-camera` and `dce-sel-resolution` , the SDK will automatically populate the lists and handle the camera/resolution switching. - - ```html -
-
-
-
- ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/nbj75vxu/) - - ```html -
- - -
-
-
- ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/25v08paf/) - - > By default, only 3 hard-coded resolutions (3840 x 2160, 1920 x 1080, 1280 x 720), are populated as options. You can show a customized set of options by hardcoding them. - - ```html - - ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/tnfjks4q/) - - > Generally, you need to provide a resolution that the camera supports. However, in case a camera does not support the specified resolution, it usually uses the cloest supported resolution. As a result, the selected resolution may not be the actual resolution. In this case, add an option with the class name `dce-opt-gotResolution` (as shown above) and the SDK will then use it to show the **actual resolution**. - - See also [UI customization samples](https://www.dynamsoft.com/barcode-reader/programming/javascript/samples-demos/ui-customization.html?ver=9.3.1&utm_source=guide). - -## API Documentation - -You can check out the detailed documentation about the APIs of the SDK at -[https://www.dynamsoft.com/barcode-reader/programming/javascript/api-reference/?ver=9.3.1](https://www.dynamsoft.com/barcode-reader/programming/javascript/api-reference/?ver=9.3.1). - -## System Requirements - -DBR requires the following features to work: - -- Secure context (HTTPS deployment) - - When deploying your application / website for production, make sure to serve it via a secure HTTPS connection. This is required for two reasons - - - Access to the camera video stream is only granted in a security context. Most browsers impose this restriction. - > Some browsers like Chrome may grant the access for `http://127.0.0.1` and `http://localhost` or even for pages opened directly from the local disk (`file:///...`). This can be helpful for temporary development and test. - - - Dynamsoft License requires a secure context to work. - -- `WebAssembly`, `Blob`, `URL`/`createObjectURL`, `Web Workers` - - The above four features are required for the SDK to work. - -- `MediaDevices`/`getUserMedia` - - This API is only required for in-browser video streaming. If a browser does not support this API, the [Single Frame Mode](https://www.dynamsoft.com/barcode-reader/programming/javascript/api-reference/BarcodeScanner.html?ver=9.3.1&utm_source=guide#singleframemode) will be used automatically. If the API exists but doesn't work correctly, the Single Frame Mode can be used as an alternative way to access the camera. - -- `getSettings` - - This API inspects the video input which is a `MediaStreamTrack` object about its constrainable properties. - -The following table is a list of supported browsers based on the above requirements: - - Browser Name | Version - :-: | :-: - Chrome | v59+1 - Firefox | v52+ (v55+ on Android/iOS1) - Edge2 | v16+ - Safari3 | v11+ - - 1 iOS 14.3+ is required for camera video streaming in Chrome and Firefox or Apps using webviews. - - 2 On Edge, due to strict Same-origin policy, you must host the SDK files on the same domain as your web page. - - 3 Safari v11.x already has the required features, but it has many other issues, so we recommend v12+. - -Apart from the browsers, the operating systems may impose some limitations of their own that could restrict the use of the SDK. Browser compatibility ultimately depends on whether the browser on that particular operating system supports the features listed above. - -## How to Upgrade - -If you want to upgrade the SDK from an old version to a newer one, please see [how to upgrade](https://www.dynamsoft.com/barcode-reader/programming/javascript/upgrade-guide/?ver=9.3.1&utm_source=guide). - -## Release Notes - -Learn about what are included in each release at [https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/release-notes/?ver=latest](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/release-notes/?ver=latest). - -## Next Steps - -Now that you have got the SDK integrated, you can choose to move forward in the following directions - -1. Check out the [Official Samples and Demo](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/index.html?ver=latest) -2. Learn how to make use of the [SDK features](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/user-guide/explore-features/index.html?ver=latest) -3. See how the SDK works in [Popular Use Cases](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/user-guide/use-cases/index.html?ver=latest) diff --git a/programming-old/javascript/user-guide/index-v9.6.1.md b/programming-old/javascript/user-guide/index-v9.6.1.md deleted file mode 100644 index 31a1bfa1..00000000 --- a/programming-old/javascript/user-guide/index-v9.6.1.md +++ /dev/null @@ -1,517 +0,0 @@ ---- -layout: default-layout -title: v9.6.1 User Guide - Dynamsoft Barcode Reader JavaScript Edition -description: This is the user guide of Dynamsoft Barcode Reader JavaScript SDK. -keywords: user guide, javascript, js -breadcrumbText: User Guide -noTitleIndex: true -needGenerateH3Content: true -needAutoGenerateSidebar: true -permalink: /programming/javascript/user-guide/index-v9.6.1.html ---- - - - -# Barcode Reader for Your Website - User Guide - -[Dynamsoft Barcode Reader JavaScript Edition](https://www.dynamsoft.com/barcode-reader/sdk-javascript/) (DBR-JS) is equipped with industry-leading algorithms for exceptional speed, accuracy and read rates in barcode reading. Using its well-designed API, you can turn your web page into a barcode scanner with just a few lines of code. - -![version](https://img.shields.io/npm/v/dynamsoft-javascript-barcode.svg) -![downloads](https://img.shields.io/npm/dm/dynamsoft-javascript-barcode.svg) -![jsdelivr](https://img.shields.io/jsdelivr/npm/hm/dynamsoft-javascript-barcode.svg) -![vulnerabilities](https://img.shields.io/snyk/vulnerabilities/npm/dynamsoft-javascript-barcode.svg) - -Once the DBR-JS SDK gets integrated into your web page, your users can access a camera via the browser and read barcodes directly from its video input. - -In this guide, you will learn step by step on how to integrate the DBR-JS SDK into your website. - -Table of Contents - -- [Barcode Reader for Your Website - User Guide](#barcode-reader-for-your-website---user-guide) - - [Hello World - Simplest Implementation](#hello-world---simplest-implementation) - - [Understand the code](#understand-the-code) - - [About the code](#about-the-code) - - [Run the example](#run-the-example) - - [Building your own page](#building-your-own-page) - - [Include the SDK](#include-the-sdk) - - [Use a public CDN](#use-a-public-cdn) - - [Host the SDK yourself](#host-the-sdk-yourself) - - [Configure the SDK](#configure-the-sdk) - - [Specify the license](#specify-the-license) - - [Specify the location of the "engine" files](#specify-the-location-of-the-engine-files) - - [Interact with the SDK](#interact-with-the-sdk) - - [Create a `BarcodeScanner` object](#create-a-barcodescanner-object) - - [Customize the `BarcodeScanner` Settings (optional)](#customize-the-barcodescanner-settings-optional) - - [Customize the UI (optional)](#customize-the-ui-optional) - - [Modify the file `dist/dbr.ui.html` directly](#modify-the-file-distdbruihtml-directly) - - [Copy the file `dist/dbr.ui.html` to your application, modify it and use the the API `defaultUIElementURL` to set it as the default UI](#copy-the-file-distdbruihtml-to-your-application-modify-it-and-use-the-the-api-defaultuielementurl-to-set-it-as-the-default-ui) - - [Append the default UI element to your page, customize it before showing it](#append-the-default-ui-element-to-your-page-customize-it-before-showing-it) - - [Build the UI element from scratch and connect it to the SDK with the API setUIElement(HTMLElement)](#build-the-ui-element-from-scratch-and-connect-it-to-the-sdk-with-the-api-setuielementhtmlelement) - - [API Documentation](#api-documentation) - - [System Requirements](#system-requirements) - - [How to Upgrade](#how-to-upgrade) - - [Release Notes](#release-notes) - - [Next Steps](#next-steps) - -**Popular Examples** - -- Hello World - [Guide](#hello-world---simplest-implementation) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.1/1.hello-world/1.hello-world.html) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/1.hello-world.html?ver=9.6.1&utm_source=guide) -- Angular App - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/helloworld-angular.html?ver=9.6.1&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.1/1.hello-world/3.read-video-angular) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/3.read-video-angular/dist/hello-world/?ver=9.6.1&utm_source=guide) -- React App - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/helloworld-reactjs.html?ver=9.6.1&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.1/1.hello-world/4.read-video-react) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/4.read-video-react/build/?ver=9.6.1&utm_source=guide) -- Vue App - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/helloworld-vuejsv3.html?ver=9.6.1&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.1/1.hello-world/6.read-video-vue3) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/6.read-video-vue3/dist/?ver=9.6.1&utm_source=guide) -- PWA App - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/helloworld-pwa.html?ver=9.6.1&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.1/1.hello-world/10.read-video-pwa) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/10.read-video-pwa/helloworld-pwa.html?ver=9.6.1&utm_source=guide) -- Read Driver Licenses - [Guide](https://www.dynamsoft.com/barcode-reader/docs/core/programming/usecases/scan-and-parse-AAMVA.html?ver=9.6.1&utm_source=guide&&lang=js) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.1/4.use-case/2.read-a-drivers-license.html) \| [Run](https://demo.dynamsoft.com/samples/dbr/js/4.use-case/2.read-a-drivers-license.html?ver=9.6.1&utm_source=guide) -- Fill A Form - [Guide](https://www.dynamsoft.com/barcode-reader/docs/core/programming/usecases/scan-barcodes-as-input.html?lang=js&&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.1/4.use-case/1.fill-a-form-with-barcode-reading.html) \| [Run](https://demo.dynamsoft.com/samples/dbr/js/4.use-case/1.fill-a-form-with-barcode-reading.html?ver=9.6.1&utm_source=guide) - -You can also: - -- Try the Official Demo - [Run](https://demo.dynamsoft.com/barcode-reader-js/?ver=9.6.1&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-demo/) -- Try Online Examples - [Run](https://demo.dynamsoft.com/Samples/DBR/JS/index.html?ver=9.6.1&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/v9.6.1/) - -## Hello World - Simplest Implementation - -Let's start with the "Hello World" example of the DBR-JS SDK which demonstrates how to use the minimum code to enable a web page to read barcodes from a live video stream. - -- Basic Requirements - - Internet connection - - [A supported browser](#system-requirements) - - Camera access - -### Understand the code - -The complete code of the "Hello World" example is shown below - -```html - - - - - - - - - -``` - -

- - Code in Github - -   - - Run via JSFiddle - -   - - Run in Dynamsoft - -

- ------ - -#### About the code - -- The DBR-JS SDK is included in the code via the **jsDelivr** CDN. - -> In some rare cases, you might not be able to access the CDN. If this happens, you can use [https://download2.dynamsoft.com/dbr/dynamsoft-barcode-reader-js/dynamsoft-barcode-reader-js-9.6.1/dist/dbr.js](https://download2.dynamsoft.com/dbr/dynamsoft-barcode-reader-js/dynamsoft-barcode-reader-js-9.6.1/dist/dbr.js) for the test. However, please DO NOT use it in your production application because it is temporary. Instead, you can try [hosting the SDK yourself](#host-the-sdk-yourself). - -- `license`: This property specifies a license key. Note that the license "DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9" used in this example is an online license and requires network connection to work. Read more on [Specify the license](#specify-the-license). - -- `createInstance()`: This method creates a `BarcodeScanner` object. This object can read barcodes directly from a video input with the help of its interactive UI (hidden by default) and the MediaDevices interface. - -- `onFrameRead`: This event is triggered every time the SDK finishes scanning a video frame. The `results` object contains all the barcode results that the SDK have found on this frame. In this example, we print the results to the browser console. - -- `onUniqueRead`: This event is triggered when the SDK finds a new barcode, which is not a duplicate among multiple frames. `txt` holds the barcode text value while `result` is an object that holds details of the barcode. In this example, an alert will be displayed for this new barcode. - -- `show()`: This method brings up the built-in UI of the `BarcodeScanner` object and starts scanning. - -### Run the example - -You can run the example deployed to the Dynamsoft Demo Server or test it with JSFiddle code editor. You will be asked to allow access to your camera, after which the video will be displayed on the page. After that, you can point the camera at a barcode to read it. - -When a barcode is decoded, you will see the result text pop up and the barcode location will be highlighted in the video feed. - -Alternatively, you can make a local test simply by taking the code in step 1, pasting it in a file with the name "hello-world.html" and open it in a browser. - -*Note*: - -If you open the web page as `file:///` or `http://` , the camera may not work correctly because the API getUserMedia usually requires HTTPS to access the camera. - -To make sure your web application can access the camera, please configure your web server to support HTTPS. The following links may help. - -1. NGINX: Configuring HTTPS servers -2. IIS: Create a Self Signed Certificate in IIS -3. Tomcat: Setting Up SSL on Tomcat in 5 minutes -4. Node.js: npm tls - -If the test doesn't go as expected, you can [contact us](https://www.dynamsoft.com/contact/?ver=9.6.1&utm_source=guide). - - - -## Building your own page - -### Include the SDK - -#### Use a public CDN - -The simplest way to include the SDK is to use either the [jsDelivr](https://jsdelivr.com/) or [UNPKG](https://unpkg.com/) CDN. The "hello world" example above uses **jsDelivr**. - -- jsDelivr - - ```html - - ``` - -- UNPKG - - ```html - - ``` - -#### Host the SDK yourself - -Besides using the public CDN, you can also download the SDK and host its files on your own server or a commercial CDN before including it in your application. - -Options to download the SDK: - -- From the website - - Download the JavaScript Package - -- yarn - - ```cmd - yarn add dynamsoft-javascript-barcode - ``` - -- npm - - ```cmd - npm install dynamsoft-javascript-barcode --save - ``` - -Depending on how you downloaded the SDK and how you intend to use it, you can typically include it like this: - -```html - -``` - -or - -```html - -``` - -or - -```typescript -import { BarcodeScanner } from 'dynamsoft-javascript-barcode'; -``` - -**NOTE** - -* Some older web application servers do not set `.wasm` mimetype as `application/wasm`. Upgrade your web application servers, or define the mimetype yourselves: - * [Apache](https://developer.mozilla.org/en-US/docs/Learn/Server-side/Apache_Configuration_htaccess#media_types_and_character_encodings) - * [IIS](https://docs.microsoft.com/en-us/iis/configuration/system.webserver/staticcontent/mimemap) - * [Nginx](https://www.nginx.com/resources/wiki/start/topics/examples/full/#mime-types) - -* To work properly, the SDK requires a few engine files, which are relatively large and may take quite a few seconds to download. We recommend that you set a longer cache time for these engine files, to maximize the performance of your web application. - - ```cmd - Cache-Control: max-age=31536000 - ``` - - Reference: [Cache-Control](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control). - -### Configure the SDK - -Before using the SDK, you need to configure a few things. - -#### Specify the license - -The SDK requires a license to work, use the API `license` to specify a license key. - -```javascript -Dynamsoft.DBR.BarcodeScanner.license = "YOUR-LICENSE-KEY"; -``` - -To test the SDK, you can request a 30-day trial license via the Request a Trial License link. - -> If you register a Dynamsoft account and download the SDK from the official website, Dynamsoft will automatically generate a 30-day trial license for you, and put the license key into all the samples attached to the SDK. - -#### Specify the location of the "engine" files - -This is usually only required with frameworks like Angular or React, etc. where dbr.js is compiled into another file. - -The purpose is to tell the SDK where to find the engine files (\*.worker.js, \*.wasm.js and \*.wasm, etc.). The API is called `engineResourcePath`: - -```javascript -//The following code uses the jsDelivr CDN, feel free to change it to your own location of these files -Dynamsoft.DBR.BarcodeScanner.engineResourcePath = "https://cdn.jsdelivr.net/npm/dynamsoft-javascript-barcode@9.6.1/dist/"; -``` - -### Interact with the SDK - -#### Create a `BarcodeScanner` object - -You can use one of two classes ( `BarcodeScanner` and `BarcodeReader` ) to interact with the SDK. `BarcodeReader` is a low-level class that processes images directly. `BarcodeScanner` , on the other hand, inherits from `BarcodeReader` and provides high-level APIs and a built-in GUI to allow continuous barcode scanning on video frames. We'll focus on `BarcodeScanner` in this guide. - -To use the SDK, we first create a `BarcodeScanner` object. - -```javascript -Dynamsoft.DBR.BarcodeScanner.license = "YOUR-LICENSE-KEY"; -let scanner = null; -try { - scanner = await Dynamsoft.DBR.BarcodeScanner.createInstance(); -} catch (ex) { - console.error(ex); -} -``` - -Tip: When creating a `BarcodeScanner` object within a function which may be called more than once, it's best to use a "helper" variable to avoid double creation such as `pScanner` in the following code - -```javascript -Dynamsoft.DBR.BarcodeScanner.license = "YOUR-LICENSE-KEY"; -let pScanner = null; -document.getElementById('btn-scan').addEventListener('click', async () => { - try { - const scanner = await (pScanner = pScanner || Dynamsoft.DBR.BarcodeScanner.createInstance()); - } catch (ex) { - console.error(ex); - } -}); -``` - -#### Customize the `BarcodeScanner` Settings (optional) - -Let's take a look at the following code snippets: - -```javascript -// Sets which camera and what resolution to use -let allCameras = await scanner.getAllCameras(); -await scanner.setCurrentCamera(allCameras[0].deviceId); -await scanner.setResolution(1280, 720); -``` - -```javascript -// Sets up the scanner behavior -let scanSettings = await scanner.getScanSettings(); -// Disregards duplicated results found in a specified time period (in milliseconds). -scanSettings.duplicateForgetTime = 5000; // The default is 3000 -// Sets a scan interval in milliseconds so the SDK may release the CPU from time to time. -// (setting this value larger is a simple way to save battery power and reduce device heating). -scanSettings.intervalTime = 100; // The default is 0. -// Sets captureAndDecodeInParallel to false, which tells the SDK not to acquire the next frame while decoding the first. -// This is another way to save battery power and is recommended on low-end phones. However, it does slow down the decoding speed. -scanSettings.captureAndDecodeInParallel = false; // The default is true. -await scanner.updateScanSettings(scanSettings); -``` - -```javascript -// Uses one of the built-in RuntimeSetting templates: "single" (decode a single barcode, the default mode), "speed", "balance", "coverage", "dense" and "distance" -await scanner.updateRuntimeSettings("speed"); - -// Makes changes to the template. The code below demonstrates how to specify enabled symbologies -let runtimeSettings = await scanner.getRuntimeSettings(); -runtimeSettings.barcodeFormatIds = Dynamsoft.DBR.EnumBarcodeFormat.BF_ONED | Dynamsoft.DBR.EnumBarcodeFormat.BF_QR_CODE; -await scanner.updateRuntimeSettings(runtimeSettings); -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/yfkcajxz/) - -As you can see from the above code snippets, there are three types of configurations: - -- Customize the data source: This configuration includes which camera to use, the preferred resolution, etc. Learn more here. - -- `get/updateScanSettings`: Configures the behavior of the scanner which includes `duplicateForgetTime` and `intervalTime`, etc. - -- `get/updateRuntimeSettings`: Configures the decode engine with either a built-in template or a comprehensive `RuntimeSettings` object. For example, the following uses the built-in "speed" settings with updated `localizationModes`. - - ```javascript - await barcodeScanner.updateRuntimeSettings("speed"); - //await barcodeScanner.updateRuntimeSettings("balance"); //alternative - //await barcodeScanner.updateRuntimeSettings("coverage"); //alternative - let settings = await barcodeScanner.getRuntimeSettings(); - settings.localizationModes = [ - Dynamsoft.DBR.EnumLocalizationMode.LM_CONNECTED_BLOCKS, - Dynamsoft.DBR.EnumLocalizationMode.LM_SCAN_DIRECTLY, - Dynamsoft.DBR.EnumLocalizationMode.LM_LINES, 0, 0, 0, 0, 0 - ]; - await barcodeScanner.updateRuntimeSettings(settings); - ``` - - Try in [JSFiddle](https://jsfiddle.net/DynamsoftTeam/f24h8c1m/). - - See also [settings samples](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/parameter-settings.html?ver=9.6.1&utm_source=guide). - -> Find the full list of the runtime settings here. - -### Customize the UI (optional) - -The built-in UI of the `BarcodeScanner` object is defined in the file `dist/dbr.ui.html` . There are a few ways to customize it: - -#### Modify the file `dist/dbr.ui.html` directly - - This option is only possible when you [Host the SDK yourself](#host-the-sdk-yourself) instead of using a public CDN. - -#### Copy the file `dist/dbr.ui.html` to your application, modify it and use the the API `defaultUIElementURL` to set it as the default UI - - ```javascript - // This line only takes effect before the method `createInstance()` is called. - Dynamsoft.DBR.BarcodeScanner.defaultUIElementURL = "THE-URL-TO-THE-FILE"; - ``` - -#### Append the default UI element to your page, customize it before showing it - - ```html -
- ``` - - ```javascript - document.getElementById('div-ui-container').appendChild(scanner.getUIElement()); - document.getElementsByClassName('dce-btn-close')[0].hidden = true; // Hide the close button - ``` - -#### Build the UI element from scratch and connect it to the SDK with the API setUIElement(HTMLElement) - -1. **Embed the video** - - ```html -
-
-
- - ``` - - > 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` . - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/2jzeq1r6/) - -2. **[Optional] Add the camera list and resolution list** - - If the class names of the created select elements match the default class names, i.e. `dce-sel-camera` and `dce-sel-resolution` respectively, the SDK will automatically populate the lists and handle the camera/resolution switching. - - ```html -
-
-
-
- ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/nbj75vxu/) - - ```html -
- - -
-
-
- ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/25v08paf/) - - > By default, only 3 hard-coded resolutions (1920 x 1080, 1280 x 720,640 x 480) are populated as options. You can show a customized set of options by hardcoding them. - - ```html - - ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/tnfjks4q/) - - > Generally, you need to provide a resolution that the camera supports. However, in case a camera does not support the specified resolution, it usually uses the cloest supported resolution. As a result, the selected resolution may not be the actual resolution. In this case, add an option with the class name `dce-opt-gotResolution` (as shown above) and the SDK will automatically use it to show the **actual resolution**. - - See the section of the Explore Features guide on [UI customization]({{site.features}}customize-the-ui.html?lang=js) to learn more. - -## API Documentation - -You can check out the detailed documentation about the APIs of the SDK at -[https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/?ver=9.6.1](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/?ver=9.6.1). - -## System Requirements - -DBR requires the following features to work: - -- Secure context (HTTPS deployment) - - When deploying your application / website for production, make sure to serve it via a secure HTTPS connection. This is required for two reasons - - - Access to the camera video stream is only granted in a security context. Most browsers impose this restriction. - > Some browsers like Chrome may grant the access for `http://127.0.0.1` and `http://localhost` or even for pages opened directly from the local disk (`file:///...`). This can be helpful for temporary development and test. - - - Dynamsoft License requires a secure context to work. - -- `WebAssembly`, `Blob`, `URL`/`createObjectURL`, `Web Workers` - - The above four features are required for the SDK to work. - -- `MediaDevices`/`getUserMedia` - - This API is only required for in-browser video streaming. If a browser does not support this API, the [Single Frame Mode](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/BarcodeScanner.html?ver=9.6.1&utm_source=guide#singleframemode) will be used automatically. If the API exists but doesn't work correctly, the Single Frame Mode can be used as an alternative way to access the camera. - -- `getSettings` - - This API inspects the video input which is a `MediaStreamTrack` object about its constrainable properties. - -The following table is a list of supported browsers based on the above requirements: - - Browser Name | Version - :-: | :-: - Chrome | v59+1 - Firefox | v52+ (v55+ on Android/iOS1) - Edge2 | v16+ - Safari3 | v11+ - - 1 iOS 14.3+ is required for camera video streaming in Chrome and Firefox or Apps using webviews. - - 2 On Edge, due to strict Same-origin policy, you must host the SDK files on the same domain as your web page. - - 3 Safari v11.x already has the required features, but it has many other issues, so we recommend v12+. - -Apart from the browsers, the operating systems may impose some limitations of their own that could restrict the use of the SDK. Browser compatibility ultimately depends on whether the browser on that particular operating system supports the features listed above. - -## How to Upgrade - -If you want to upgrade the SDK from an old version to a newer one, please see [how to upgrade](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/upgrade-guide/?ver=9.6.1&utm_source=guide). - -## Release Notes - -Learn about what are included in each release at [https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/release-notes/?ver=latest](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/release-notes/?ver=latest). - -## Next Steps - -Now that you have got the SDK integrated, you can choose to move forward in the following directions - -1. Check out the [Official Samples and Demo](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/index.html?ver=latest) -2. Learn how to make use of the [SDK features](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/user-guide/explore-features/index.html?ver=latest) -3. See how the SDK works in [Popular Use Cases](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/user-guide/use-cases/index.html?ver=latest) diff --git a/programming-old/javascript/user-guide/index-v9.6.10.md b/programming-old/javascript/user-guide/index-v9.6.10.md deleted file mode 100644 index 0486a552..00000000 --- a/programming-old/javascript/user-guide/index-v9.6.10.md +++ /dev/null @@ -1,513 +0,0 @@ ---- -layout: default-layout -title: v9.6.10 User Guide - Dynamsoft Barcode Reader JavaScript Edition -description: This is the user guide of Dynamsoft Barcode Reader JavaScript SDK. -keywords: user guide, javascript, js -breadcrumbText: User Guide -noTitleIndex: true -needGenerateH3Content: true -needAutoGenerateSidebar: true -permalink: /programming/javascript/user-guide/index-v9.6.10.html -schema: schemas/dynamsoft-facilitates-mit-research-schema.json ---- - - - -# Barcode Reader for Your Website - User Guide - -[Dynamsoft Barcode Reader JavaScript Edition](https://www.dynamsoft.com/barcode-reader/sdk-javascript/) (DBR-JS) is equipped with industry-leading algorithms for exceptional speed, accuracy and read rates in barcode reading. Using its well-designed API, you can turn your web page into a barcode scanner with just a few lines of code. - -![version](https://img.shields.io/npm/v/dynamsoft-javascript-barcode.svg) -![downloads](https://img.shields.io/npm/dm/dynamsoft-javascript-barcode.svg) -![jsdelivr](https://img.shields.io/jsdelivr/npm/hm/dynamsoft-javascript-barcode.svg) -![vulnerabilities](https://img.shields.io/snyk/vulnerabilities/npm/dynamsoft-javascript-barcode.svg) - -Once the DBR-JS SDK gets integrated into your web page, your users can access a camera via the browser and read barcodes directly from its video input. - - - -In this guide, you will learn step by step on how to integrate the DBR-JS SDK into your website. - -Table of Contents - -- [Hello World - Simplest Implementation](#hello-world---simplest-implementation) - - [Understand the code](#understand-the-code) - - [Run the example](#run-the-example) -- [Building your own page](#building-your-own-page) - - [Include the SDK](#include-the-sdk) - - [Configure the SDK](#configure-the-sdk) - - [Interact with the SDK](#interact-with-the-sdk) - - [Customize the UI (optional)](#customize-the-ui-optional) -- [API Documentation](#api-documentation) -- [System Requirements](#system-requirements) -- [How to Upgrade](#how-to-upgrade) -- [Release Notes](#release-notes) -- [Next Steps](#next-steps) - -**Popular Examples** - -- Hello World - [Guide](#hello-world---simplest-implementation) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.10/1.hello-world/1.hello-world.html) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/1.hello-world.html?ver=9.6.10&utm_source=guide) -- Angular App - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/helloworld-angular.html?ver=9.6.10&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.10/1.hello-world/3.read-video-angular) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/3.read-video-angular/dist/hello-world/?ver=9.6.10&utm_source=guide) -- React App - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/helloworld-reactjs.html?ver=9.6.10&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.10/1.hello-world/4.read-video-react) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/4.read-video-react/build/?ver=9.6.10&utm_source=guide) -- Vue App - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/helloworld-vuejsv3.html?ver=9.6.10&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.10/1.hello-world/6.read-video-vue3) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/6.read-video-vue3/dist/?ver=9.6.10&utm_source=guide) -- PWA App - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/helloworld-pwa.html?ver=9.6.10&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.10/1.hello-world/10.read-video-pwa) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/10.read-video-pwa/helloworld-pwa.html?ver=9.6.10&utm_source=guide) -- Read Driver Licenses - [Guide](https://www.dynamsoft.com/barcode-reader/docs/core/programming/usecases/scan-and-parse-AAMVA.html?ver=9.6.10&utm_source=guide&&lang=js) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.10/4.use-case/2.read-a-drivers-license.html) \| [Run](https://demo.dynamsoft.com/samples/dbr/js/4.use-case/2.read-a-drivers-license.html?ver=9.6.10&utm_source=guide) -- Fill A Form - [Guide](https://www.dynamsoft.com/barcode-reader/docs/core/programming/usecases/scan-barcodes-as-input.html?lang=js&&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.10/4.use-case/1.fill-a-form-with-barcode-reading.html) \| [Run](https://demo.dynamsoft.com/samples/dbr/js/4.use-case/1.fill-a-form-with-barcode-reading.html?ver=9.6.10&utm_source=guide) -- Debug Camera and Collect Video Frame - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/debug.html?lang=js&&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.10/5.others/debug) - -You can also: - -- Try the Official Demo - [Run](https://demo.dynamsoft.com/barcode-reader-js/?ver=9.6.10&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-demo/) -- Try Online Examples - [Run](https://demo.dynamsoft.com/Samples/DBR/JS/index.html?ver=9.6.10&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/v9.6.10/) - -## Hello World - Simplest Implementation - -Let's start with the "Hello World" example of the DBR-JS SDK which demonstrates how to use the minimum code to enable a web page to read barcodes from a live video stream. - -- Basic Requirements - - Internet connection - - [A supported browser](#system-requirements) - - Camera access - -### Understand the code - -The complete code of the "Hello World" example is shown below - -```html - - - - - - - - - -``` - -

- - Code in Github - -   - - Run via JSFiddle - -   - - Run in Dynamsoft - -

- ------ - -#### About the code - -- The DBR-JS SDK is included in the code via the **jsDelivr** CDN. - -> In some rare cases, you might not be able to access the CDN. If this happens, you can use [https://download2.dynamsoft.com/dbr/dynamsoft-barcode-reader-js/dynamsoft-barcode-reader-js-9.6.10/dist/dbr.js](https://download2.dynamsoft.com/dbr/dynamsoft-barcode-reader-js/dynamsoft-barcode-reader-js-9.6.10/dist/dbr.js) for the test. However, please DO NOT use CDN of `download2.dynamsoft.com` in your production application because it is temporary. Instead, you can try [hosting the SDK yourself](#host-the-sdk-yourself). - -- `license`: This property specifies a license key. Note that the license "DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9" used in this example is an online license and requires network connection to work. Read more on [Specify the license](#specify-the-license). - -- `createInstance()`: This method creates a `BarcodeScanner` object. This object can read barcodes directly from a video input with the help of its interactive UI (hidden by default) and the MediaDevices interface. - -- `onFrameRead`: This event is triggered every time the SDK finishes scanning a video frame. The `results` object contains all the barcode results that the SDK have found on this frame. In this example, we print the results to the browser console. - -- `onUniqueRead`: This event is triggered when the SDK finds a new barcode, which is not a duplicate among multiple frames. `txt` holds the barcode text value while `result` is an object that holds details of the barcode. In this example, an alert will be displayed for this new barcode. - -- `show()`: This method brings up the built-in UI of the `BarcodeScanner` object and starts scanning. - -### Run the example - -You can run the example deployed to the Dynamsoft Demo Server or test it with JSFiddle code editor. You will be asked to allow access to your camera, after which the video will be displayed on the page. After that, you can point the camera at a barcode to read it. - -When a barcode is decoded, you will see the result text pop up and the barcode location will be highlighted in the video feed. - -Alternatively, you can make a local test simply by taking the code in step 1, pasting it in a file with the name "hello-world.html" and open it in a browser. - -*Note*: - -If you open the web page as `file:///` or `http://` , the camera may not work correctly because the API getUserMedia usually requires HTTPS to access the camera. - -To make sure your web application can access the camera, please configure your web server to support HTTPS. The following links may help. - -1. NGINX: Configuring HTTPS servers -2. IIS: Create a Self Signed Certificate in IIS -3. Tomcat: Setting Up SSL on Tomcat in 5 minutes -4. Node.js: npm tls - -If the test doesn't go as expected, you can [contact us](https://www.dynamsoft.com/contact/?ver=9.6.10&utm_source=guide). - -**Pinned Message:** - -- [Temporary solution for iPhone 14 Pro Max rear camera not focusing](https://github.com/Dynamsoft/barcode-reader-javascript-samples/issues/99#issuecomment-1407584605) - -## Building your own page - -### Include the SDK - -#### Use a public CDN - -The simplest way to include the SDK is to use either the [jsDelivr](https://jsdelivr.com/) or [UNPKG](https://unpkg.com/) CDN. The "hello world" example above uses **jsDelivr**. - -- jsDelivr - - ```html - - ``` - -- UNPKG - - ```html - - ``` - -#### Host the SDK yourself - -Besides using the public CDN, you can also download the SDK and host its files on your own server or a commercial CDN before including it in your application. - -Options to download the SDK: - -- From the website - - Download the JavaScript Package - -- yarn - - ```cmd - yarn add dynamsoft-javascript-barcode - ``` - -- npm - - ```cmd - npm install dynamsoft-javascript-barcode --save - ``` - -Depending on how you downloaded the SDK and how you intend to use it, you can typically include it like this: - -```html - -``` - -or - -```html - -``` - -or - -```typescript -import { BarcodeScanner } from 'dynamsoft-javascript-barcode'; -``` - -**NOTE** - -* Some older web application servers do not set `.wasm` mimetype as `application/wasm`. Upgrade your web application servers, or define the mimetype yourselves: - * [Apache](https://developer.mozilla.org/en-US/docs/Learn/Server-side/Apache_Configuration_htaccess#media_types_and_character_encodings) - * [IIS](https://docs.microsoft.com/en-us/iis/configuration/system.webserver/staticcontent/mimemap) - * [Nginx](https://www.nginx.com/resources/wiki/start/topics/examples/full/#mime-types) - -* To work properly, the SDK requires a few engine files, which are relatively large and may take quite a few seconds to download. We recommend that you set a longer cache time for these engine files, to maximize the performance of your web application. - - ```cmd - Cache-Control: max-age=31536000 - ``` - - Reference: [Cache-Control](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control). - -### Configure the SDK - -Before using the SDK, you need to configure a few things. - -#### Specify the license - -The SDK requires a license to work, use the API `license` to specify a license key. - -```javascript -Dynamsoft.DBR.BarcodeScanner.license = "YOUR-LICENSE-KEY"; -``` - -To test the SDK, you can request a 30-day trial license via the Request a Trial License link. - -> If you register a Dynamsoft account and download the SDK from the official website, Dynamsoft will automatically generate a 30-day trial license for you, and put the license key into all the samples attached to the SDK. - -#### Specify the location of the "engine" files - -This is usually only required with frameworks like Angular or React, etc. where dbr.js is compiled into another file. - -The purpose is to tell the SDK where to find the engine files (\*.worker.js, \*.wasm.js and \*.wasm, etc.). The API is called `engineResourcePath`: - -```javascript -//The following code uses the jsDelivr CDN, feel free to change it to your own location of these files -Dynamsoft.DBR.BarcodeScanner.engineResourcePath = "https://cdn.jsdelivr.net/npm/dynamsoft-javascript-barcode@9.6.10/dist/"; -``` - -### Interact with the SDK - -#### Create a `BarcodeScanner` object - -You can use one of two classes ( `BarcodeScanner` and `BarcodeReader` ) to interact with the SDK. `BarcodeReader` is a low-level class that processes images directly. `BarcodeScanner` , on the other hand, inherits from `BarcodeReader` and provides high-level APIs and a built-in GUI to allow continuous barcode scanning on video frames. We'll focus on `BarcodeScanner` in this guide. - -To use the SDK, we first create a `BarcodeScanner` object. - -```javascript -Dynamsoft.DBR.BarcodeScanner.license = "YOUR-LICENSE-KEY"; -let scanner = null; -try { - scanner = await Dynamsoft.DBR.BarcodeScanner.createInstance(); -} catch (ex) { - console.error(ex); -} -``` - -Tip: When creating a `BarcodeScanner` object within a function which may be called more than once, it's best to use a "helper" variable to avoid double creation such as `pScanner` in the following code - -```javascript -Dynamsoft.DBR.BarcodeScanner.license = "YOUR-LICENSE-KEY"; -let pScanner = null; -document.getElementById('btn-scan').addEventListener('click', async () => { - try { - const scanner = await (pScanner = pScanner || Dynamsoft.DBR.BarcodeScanner.createInstance()); - } catch (ex) { - console.error(ex); - } -}); -``` - -#### Customize the `BarcodeScanner` Settings (optional) - -Let's take a look at the following code snippets: - -```javascript -// Sets which camera and what resolution to use -let allCameras = await scanner.getAllCameras(); -await scanner.setCurrentCamera(allCameras[0].deviceId); -await scanner.setResolution(1280, 720); -``` - -```javascript -// Sets up the scanner behavior -let scanSettings = await scanner.getScanSettings(); -// Disregards duplicated results found in a specified time period (in milliseconds). -scanSettings.duplicateForgetTime = 5000; // The default is 3000 -// Sets a scan interval in milliseconds so the SDK may release the CPU from time to time. -// (setting this value larger is a simple way to save battery power and reduce device heating). -scanSettings.intervalTime = 100; // The default is 0. -// Sets captureAndDecodeInParallel to false, which tells the SDK not to acquire the next frame while decoding the first. -// This is another way to save battery power and is recommended on low-end phones. However, it does slow down the decoding speed. -scanSettings.captureAndDecodeInParallel = false; // The default is true. -await scanner.updateScanSettings(scanSettings); -``` - -```javascript -// Uses one of the built-in RuntimeSetting templates: "single" (decode a single barcode, the default mode), "speed", "balance", "coverage", "dense" and "distance" -await scanner.updateRuntimeSettings("speed"); - -// Makes changes to the template. The code below demonstrates how to specify enabled symbologies -let runtimeSettings = await scanner.getRuntimeSettings(); -runtimeSettings.barcodeFormatIds = Dynamsoft.DBR.EnumBarcodeFormat.BF_ONED | Dynamsoft.DBR.EnumBarcodeFormat.BF_QR_CODE; -await scanner.updateRuntimeSettings(runtimeSettings); -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/yfkcajxz/) - -As you can see from the above code snippets, there are three types of configurations: - -- Customize the data source: This configuration includes which camera to use, the preferred resolution, etc. Learn more here. - -- `get/updateScanSettings`: Configures the behavior of the scanner which includes `duplicateForgetTime` and `intervalTime`, etc. - -- `get/updateRuntimeSettings`: Configures the decode engine with either a built-in template or a comprehensive `RuntimeSettings` object. For example, the following uses the built-in "speed" settings with updated `localizationModes`. - - ```javascript - await barcodeScanner.updateRuntimeSettings("speed"); - //await barcodeScanner.updateRuntimeSettings("balance"); //alternative - //await barcodeScanner.updateRuntimeSettings("coverage"); //alternative - let settings = await barcodeScanner.getRuntimeSettings(); - settings.localizationModes = [ - Dynamsoft.DBR.EnumLocalizationMode.LM_CONNECTED_BLOCKS, - Dynamsoft.DBR.EnumLocalizationMode.LM_SCAN_DIRECTLY, - Dynamsoft.DBR.EnumLocalizationMode.LM_LINES, 0, 0, 0, 0, 0 - ]; - await barcodeScanner.updateRuntimeSettings(settings); - ``` - - Try in [JSFiddle](https://jsfiddle.net/DynamsoftTeam/f24h8c1m/). - - See also [settings samples](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/parameter-settings.html?ver=9.6.10&utm_source=guide). - -> Find the full list of the runtime settings here. - -### Customize the UI (optional) - -The built-in UI of the `BarcodeScanner` object is defined in the file `dist/dbr.ui.html` . There are a few ways to customize it: - -#### Modify the file `dist/dbr.ui.html` directly - - This option is only possible when you [Host the SDK yourself](#host-the-sdk-yourself) instead of using a public CDN. - -#### Copy the file `dist/dbr.ui.html` to your application, modify it and use the the API `defaultUIElementURL` to set it as the default UI - - ```javascript - // This line only takes effect before the method `createInstance()` is called. - Dynamsoft.DBR.BarcodeScanner.defaultUIElementURL = "THE-URL-TO-THE-FILE"; - ``` - -#### Append the default UI element to your page, customize it before showing it - - ```html -
- ``` - - ```javascript - document.getElementById('div-ui-container').appendChild(scanner.getUIElement()); - document.getElementsByClassName('dce-btn-close')[0].hidden = true; // Hide the close button - ``` - -#### Build the UI element from scratch and connect it to the SDK with the API `setUIElement(HTMLElement)` - -1. **Embed the video** - - ```html -
-
-
- - ``` - - > 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` . - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/2jzeq1r6/) - -2. **[Optional] Add the camera list and resolution list** - - If the class names of the created select elements match the default class names, i.e. `dce-sel-camera` and `dce-sel-resolution` respectively, the SDK will automatically populate the lists and handle the camera/resolution switching. - - ```html -
-
-
-
- ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/nbj75vxu/) - - ```html -
- - -
-
-
- ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/25v08paf/) - - > By default, only 3 hard-coded resolutions (1920 x 1080, 1280 x 720,640 x 480) are populated as options. You can show a customized set of options by hardcoding them. - - ```html - - ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/tnfjks4q/) - - > Generally, you need to provide a resolution that the camera supports. However, in case a camera does not support the specified resolution, it usually uses the cloest supported resolution. As a result, the selected resolution may not be the actual resolution. In this case, add an option with the class name `dce-opt-gotResolution` (as shown above) and the SDK will automatically use it to show the **actual resolution**. - - See the section of the Explore Features guide on [UI customization]({{site.features}}customize-the-ui.html?lang=js) to learn more. - -## API Documentation - -You can check out the detailed documentation about the APIs of the SDK at -[https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/?ver=9.6.10](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/?ver=9.6.10). - -## System Requirements - -DBR requires the following features to work: - -- Secure context (HTTPS deployment) - - When deploying your application / website for production, make sure to serve it via a secure HTTPS connection. This is required for two reasons - - - Access to the camera video stream is only granted in a security context. Most browsers impose this restriction. - > Some browsers like Chrome may grant the access for `http://127.0.0.1` and `http://localhost` or even for pages opened directly from the local disk (`file:///...`). This can be helpful for temporary development and test. - - - Dynamsoft License requires a secure context to work. - -- `WebAssembly`, `Blob`, `URL`/`createObjectURL`, `Web Workers` - - The above four features are required for the SDK to work. - -- `MediaDevices`/`getUserMedia` - - This API is only required for in-browser video streaming. If a browser does not support this API, the [Single Frame Mode](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/BarcodeScanner.html?ver=9.6.10&utm_source=guide#singleframemode) will be used automatically. If the API exists but doesn't work correctly, the Single Frame Mode can be used as an alternative way to access the camera. - -- `getSettings` - - This API inspects the video input which is a `MediaStreamTrack` object about its constrainable properties. - -The following table is a list of supported browsers based on the above requirements: - - Browser Name | Version - :-: | :-: - Chrome | v59+1 - Firefox | v52+ (v55+ on Android/iOS1) - Edge2 | v16+ - Safari3 | v11+ - - 1 iOS 14.3+ is required for camera video streaming in Chrome and Firefox or Apps using webviews. - - 2 On Edge, due to strict Same-origin policy, you must host the SDK files on the same domain as your web page. - - 3 Safari v11.x already has the required features, but it has many other issues, so we recommend v12+. - -Apart from the browsers, the operating systems may impose some limitations of their own that could restrict the use of the SDK. Browser compatibility ultimately depends on whether the browser on that particular operating system supports the features listed above. - -## How to Upgrade - -If you want to upgrade the SDK from an old version to a newer one, please see [how to upgrade](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/upgrade-guide/?ver=9.6.10&utm_source=guide). - -## Release Notes - -Learn about what are included in each release at [https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/release-notes/?ver=latest](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/release-notes/?ver=latest). - -## Next Steps - -Now that you have got the SDK integrated, you can choose to move forward in the following directions - -1. Check out the [Official Samples and Demo](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/index.html?ver=latest) -2. Learn how to make use of the [SDK features](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/user-guide/explore-features/index.html?ver=latest) -3. See how the SDK works in [Popular Use Cases](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/user-guide/use-cases/index.html?ver=latest) diff --git a/programming-old/javascript/user-guide/index-v9.6.11.md b/programming-old/javascript/user-guide/index-v9.6.11.md deleted file mode 100644 index cb12c8be..00000000 --- a/programming-old/javascript/user-guide/index-v9.6.11.md +++ /dev/null @@ -1,513 +0,0 @@ ---- -layout: default-layout -title: v9.6.11 User Guide - Dynamsoft Barcode Reader JavaScript Edition -description: This is the user guide of Dynamsoft Barcode Reader JavaScript SDK. -keywords: user guide, javascript, js -breadcrumbText: User Guide -noTitleIndex: true -needGenerateH3Content: true -needAutoGenerateSidebar: true -permalink: /programming/javascript/user-guide/index-v9.6.11.html -schema: schemas/dynamsoft-facilitates-mit-research-schema.json ---- - - - -# Barcode Reader for Your Website - User Guide - -[Dynamsoft Barcode Reader JavaScript Edition](https://www.dynamsoft.com/barcode-reader/sdk-javascript/) (DBR-JS) is equipped with industry-leading algorithms for exceptional speed, accuracy and read rates in barcode reading. Using its well-designed API, you can turn your web page into a barcode scanner with just a few lines of code. - -![version](https://img.shields.io/npm/v/dynamsoft-javascript-barcode.svg) -![downloads](https://img.shields.io/npm/dm/dynamsoft-javascript-barcode.svg) -![jsdelivr](https://img.shields.io/jsdelivr/npm/hm/dynamsoft-javascript-barcode.svg) -![vulnerabilities](https://img.shields.io/snyk/vulnerabilities/npm/dynamsoft-javascript-barcode.svg) - -Once the DBR-JS SDK gets integrated into your web page, your users can access a camera via the browser and read barcodes directly from its video input. - - - -In this guide, you will learn step by step on how to integrate the DBR-JS SDK into your website. - -Table of Contents - -- [Hello World - Simplest Implementation](#hello-world---simplest-implementation) - - [Understand the code](#understand-the-code) - - [Run the example](#run-the-example) -- [Building your own page](#building-your-own-page) - - [Include the SDK](#include-the-sdk) - - [Configure the SDK](#configure-the-sdk) - - [Interact with the SDK](#interact-with-the-sdk) - - [Customize the UI (optional)](#customize-the-ui-optional) -- [API Documentation](#api-documentation) -- [System Requirements](#system-requirements) -- [How to Upgrade](#how-to-upgrade) -- [Release Notes](#release-notes) -- [Next Steps](#next-steps) - -**Popular Examples** - -- Hello World - [Guide](#hello-world---simplest-implementation) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.11/1.hello-world/1.hello-world.html) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/1.hello-world.html?ver=9.6.11&utm_source=guide) -- Angular App - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/helloworld-angular.html?ver=9.6.11&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.11/1.hello-world/3.read-video-angular) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/3.read-video-angular/dist/hello-world/?ver=9.6.11&utm_source=guide) -- React App - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/helloworld-reactjs.html?ver=9.6.11&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.11/1.hello-world/4.read-video-react) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/4.read-video-react/build/?ver=9.6.11&utm_source=guide) -- Vue App - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/helloworld-vuejsv3.html?ver=9.6.11&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.11/1.hello-world/6.read-video-vue3) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/6.read-video-vue3/dist/?ver=9.6.11&utm_source=guide) -- PWA App - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/helloworld-pwa.html?ver=9.6.11&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.11/1.hello-world/10.read-video-pwa) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/10.read-video-pwa/helloworld-pwa.html?ver=9.6.11&utm_source=guide) -- Read Driver Licenses - [Guide](https://www.dynamsoft.com/barcode-reader/docs/core/programming/usecases/scan-and-parse-AAMVA.html?ver=9.6.11&utm_source=guide&&lang=js) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.11/4.use-case/2.read-a-drivers-license.html) \| [Run](https://demo.dynamsoft.com/samples/dbr/js/4.use-case/2.read-a-drivers-license.html?ver=9.6.11&utm_source=guide) -- Fill A Form - [Guide](https://www.dynamsoft.com/barcode-reader/docs/core/programming/usecases/scan-barcodes-as-input.html?lang=js&&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.11/4.use-case/1.fill-a-form-with-barcode-reading.html) \| [Run](https://demo.dynamsoft.com/samples/dbr/js/4.use-case/1.fill-a-form-with-barcode-reading.html?ver=9.6.11&utm_source=guide) -- Debug Camera and Collect Video Frame - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/debug.html?lang=js&&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.11/5.others/debug) - -You can also: - -- Try the Official Demo - [Run](https://demo.dynamsoft.com/barcode-reader-js/?ver=9.6.11&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-demo/) -- Try Online Examples - [Run](https://demo.dynamsoft.com/Samples/DBR/JS/index.html?ver=9.6.11&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/v9.6.11/) - -## Hello World - Simplest Implementation - -Let's start with the "Hello World" example of the DBR-JS SDK which demonstrates how to use the minimum code to enable a web page to read barcodes from a live video stream. - -- Basic Requirements - - Internet connection - - [A supported browser](#system-requirements) - - Camera access - -### Understand the code - -The complete code of the "Hello World" example is shown below - -```html - - - - - - - - - -``` - -

- - Code in Github - -   - - Run via JSFiddle - -   - - Run in Dynamsoft - -

- ------ - -#### About the code - -- The DBR-JS SDK is included in the code via the **jsDelivr** CDN. - -> In some rare cases, you might not be able to access the CDN. If this happens, you can use [https://download2.dynamsoft.com/dbr/dynamsoft-barcode-reader-js/dynamsoft-barcode-reader-js-9.6.11/dist/dbr.js](https://download2.dynamsoft.com/dbr/dynamsoft-barcode-reader-js/dynamsoft-barcode-reader-js-9.6.11/dist/dbr.js) for the test. However, please DO NOT use CDN of `download2.dynamsoft.com` in your production application because it is temporary. Instead, you can try [hosting the SDK yourself](#host-the-sdk-yourself). - -- `license`: This property specifies a license key. Note that the license "DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9" used in this example is an online license and requires network connection to work. Read more on [Specify the license](#specify-the-license). - -- `createInstance()`: This method creates a `BarcodeScanner` object. This object can read barcodes directly from a video input with the help of its interactive UI (hidden by default) and the MediaDevices interface. - -- `onFrameRead`: This event is triggered every time the SDK finishes scanning a video frame. The `results` object contains all the barcode results that the SDK have found on this frame. In this example, we print the results to the browser console. - -- `onUniqueRead`: This event is triggered when the SDK finds a new barcode, which is not a duplicate among multiple frames. `txt` holds the barcode text value while `result` is an object that holds details of the barcode. In this example, an alert will be displayed for this new barcode. - -- `show()`: This method brings up the built-in UI of the `BarcodeScanner` object and starts scanning. - -### Run the example - -You can run the example deployed to the Dynamsoft Demo Server or test it with JSFiddle code editor. You will be asked to allow access to your camera, after which the video will be displayed on the page. After that, you can point the camera at a barcode to read it. - -When a barcode is decoded, you will see the result text pop up and the barcode location will be highlighted in the video feed. - -Alternatively, you can make a local test simply by taking the code in step 1, pasting it in a file with the name "hello-world.html" and open it in a browser. - -*Note*: - -If you open the web page as `file:///` or `http://` , the camera may not work correctly because the API getUserMedia usually requires HTTPS to access the camera. - -To make sure your web application can access the camera, please configure your web server to support HTTPS. The following links may help. - -1. NGINX: Configuring HTTPS servers -2. IIS: Create a Self Signed Certificate in IIS -3. Tomcat: Setting Up SSL on Tomcat in 5 minutes -4. Node.js: npm tls - -If the test doesn't go as expected, you can [contact us](https://www.dynamsoft.com/contact/?ver=9.6.11&utm_source=guide). - -**Pinned Message:** - -- [Temporary solution for iPhone 14 Pro Max rear camera not focusing](https://github.com/Dynamsoft/barcode-reader-javascript-samples/issues/99#issuecomment-1407584605) - -## Building your own page - -### Include the SDK - -#### Use a public CDN - -The simplest way to include the SDK is to use either the [jsDelivr](https://jsdelivr.com/) or [UNPKG](https://unpkg.com/) CDN. The "hello world" example above uses **jsDelivr**. - -- jsDelivr - - ```html - - ``` - -- UNPKG - - ```html - - ``` - -#### Host the SDK yourself - -Besides using the public CDN, you can also download the SDK and host its files on your own server or a commercial CDN before including it in your application. - -Options to download the SDK: - -- From the website - - Download the JavaScript Package - -- yarn - - ```cmd - yarn add dynamsoft-javascript-barcode - ``` - -- npm - - ```cmd - npm install dynamsoft-javascript-barcode --save - ``` - -Depending on how you downloaded the SDK and how you intend to use it, you can typically include it like this: - -```html - -``` - -or - -```html - -``` - -or - -```typescript -import { BarcodeScanner } from 'dynamsoft-javascript-barcode'; -``` - -**NOTE** - -* Some older web application servers do not set `.wasm` mimetype as `application/wasm`. Upgrade your web application servers, or define the mimetype yourselves: - * [Apache](https://developer.mozilla.org/en-US/docs/Learn/Server-side/Apache_Configuration_htaccess#media_types_and_character_encodings) - * [IIS](https://docs.microsoft.com/en-us/iis/configuration/system.webserver/staticcontent/mimemap) - * [Nginx](https://www.nginx.com/resources/wiki/start/topics/examples/full/#mime-types) - -* To work properly, the SDK requires a few engine files, which are relatively large and may take quite a few seconds to download. We recommend that you set a longer cache time for these engine files, to maximize the performance of your web application. - - ```cmd - Cache-Control: max-age=31536000 - ``` - - Reference: [Cache-Control](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control). - -### Configure the SDK - -Before using the SDK, you need to configure a few things. - -#### Specify the license - -The SDK requires a license to work, use the API `license` to specify a license key. - -```javascript -Dynamsoft.DBR.BarcodeScanner.license = "YOUR-LICENSE-KEY"; -``` - -To test the SDK, you can request a 30-day trial license via the Request a Trial License link. - -> If you register a Dynamsoft account and download the SDK from the official website, Dynamsoft will automatically generate a 30-day trial license for you, and put the license key into all the samples attached to the SDK. - -#### Specify the location of the "engine" files - -This is usually only required with frameworks like Angular or React, etc. where dbr.js is compiled into another file. - -The purpose is to tell the SDK where to find the engine files (\*.worker.js, \*.wasm.js and \*.wasm, etc.). The API is called `engineResourcePath`: - -```javascript -//The following code uses the jsDelivr CDN, feel free to change it to your own location of these files -Dynamsoft.DBR.BarcodeScanner.engineResourcePath = "https://cdn.jsdelivr.net/npm/dynamsoft-javascript-barcode@9.6.11/dist/"; -``` - -### Interact with the SDK - -#### Create a `BarcodeScanner` object - -You can use one of two classes ( `BarcodeScanner` and `BarcodeReader` ) to interact with the SDK. `BarcodeReader` is a low-level class that processes images directly. `BarcodeScanner` , on the other hand, inherits from `BarcodeReader` and provides high-level APIs and a built-in GUI to allow continuous barcode scanning on video frames. We'll focus on `BarcodeScanner` in this guide. - -To use the SDK, we first create a `BarcodeScanner` object. - -```javascript -Dynamsoft.DBR.BarcodeScanner.license = "YOUR-LICENSE-KEY"; -let scanner = null; -try { - scanner = await Dynamsoft.DBR.BarcodeScanner.createInstance(); -} catch (ex) { - console.error(ex); -} -``` - -Tip: When creating a `BarcodeScanner` object within a function which may be called more than once, it's best to use a "helper" variable to avoid double creation such as `pScanner` in the following code - -```javascript -Dynamsoft.DBR.BarcodeScanner.license = "YOUR-LICENSE-KEY"; -let pScanner = null; -document.getElementById('btn-scan').addEventListener('click', async () => { - try { - const scanner = await (pScanner = pScanner || Dynamsoft.DBR.BarcodeScanner.createInstance()); - } catch (ex) { - console.error(ex); - } -}); -``` - -#### Customize the `BarcodeScanner` Settings (optional) - -Let's take a look at the following code snippets: - -```javascript -// Sets which camera and what resolution to use -let allCameras = await scanner.getAllCameras(); -await scanner.setCurrentCamera(allCameras[0].deviceId); -await scanner.setResolution(1280, 720); -``` - -```javascript -// Sets up the scanner behavior -let scanSettings = await scanner.getScanSettings(); -// Disregards duplicated results found in a specified time period (in milliseconds). -scanSettings.duplicateForgetTime = 5000; // The default is 3000 -// Sets a scan interval in milliseconds so the SDK may release the CPU from time to time. -// (setting this value larger is a simple way to save battery power and reduce device heating). -scanSettings.intervalTime = 100; // The default is 0. -// Sets captureAndDecodeInParallel to false, which tells the SDK not to acquire the next frame while decoding the first. -// This is another way to save battery power and is recommended on low-end phones. However, it does slow down the decoding speed. -scanSettings.captureAndDecodeInParallel = false; // The default is true. -await scanner.updateScanSettings(scanSettings); -``` - -```javascript -// Uses one of the built-in RuntimeSetting templates: "single" (decode a single barcode, the default mode), "speed", "balance", "coverage", "dense" and "distance" -await scanner.updateRuntimeSettings("speed"); - -// Makes changes to the template. The code below demonstrates how to specify enabled symbologies -let runtimeSettings = await scanner.getRuntimeSettings(); -runtimeSettings.barcodeFormatIds = Dynamsoft.DBR.EnumBarcodeFormat.BF_ONED | Dynamsoft.DBR.EnumBarcodeFormat.BF_QR_CODE; -await scanner.updateRuntimeSettings(runtimeSettings); -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/yfkcajxz/) - -As you can see from the above code snippets, there are three types of configurations: - -- Customize the data source: This configuration includes which camera to use, the preferred resolution, etc. Learn more here. - -- `get/updateScanSettings`: Configures the behavior of the scanner which includes `duplicateForgetTime` and `intervalTime`, etc. - -- `get/updateRuntimeSettings`: Configures the decode engine with either a built-in template or a comprehensive `RuntimeSettings` object. For example, the following uses the built-in "speed" settings with updated `localizationModes`. - - ```javascript - await barcodeScanner.updateRuntimeSettings("speed"); - //await barcodeScanner.updateRuntimeSettings("balance"); //alternative - //await barcodeScanner.updateRuntimeSettings("coverage"); //alternative - let settings = await barcodeScanner.getRuntimeSettings(); - settings.localizationModes = [ - Dynamsoft.DBR.EnumLocalizationMode.LM_CONNECTED_BLOCKS, - Dynamsoft.DBR.EnumLocalizationMode.LM_SCAN_DIRECTLY, - Dynamsoft.DBR.EnumLocalizationMode.LM_LINES, 0, 0, 0, 0, 0 - ]; - await barcodeScanner.updateRuntimeSettings(settings); - ``` - - Try in [JSFiddle](https://jsfiddle.net/DynamsoftTeam/f24h8c1m/). - - See also [settings samples](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/parameter-settings.html?ver=9.6.11&utm_source=guide). - -> Find the full list of the runtime settings here. - -### Customize the UI (optional) - -The built-in UI of the `BarcodeScanner` object is defined in the file `dist/dbr.ui.html` . There are a few ways to customize it: - -#### Modify the file `dist/dbr.ui.html` directly - - This option is only possible when you [Host the SDK yourself](#host-the-sdk-yourself) instead of using a public CDN. - -#### Copy the file `dist/dbr.ui.html` to your application, modify it and use the the API `defaultUIElementURL` to set it as the default UI - - ```javascript - // This line only takes effect before the method `createInstance()` is called. - Dynamsoft.DBR.BarcodeScanner.defaultUIElementURL = "THE-URL-TO-THE-FILE"; - ``` - -#### Append the default UI element to your page, customize it before showing it - - ```html -
- ``` - - ```javascript - document.getElementById('div-ui-container').appendChild(scanner.getUIElement()); - document.getElementsByClassName('dce-btn-close')[0].hidden = true; // Hide the close button - ``` - -#### Build the UI element from scratch and connect it to the SDK with the API `setUIElement(HTMLElement)` - -1. **Embed the video** - - ```html -
-
-
- - ``` - - > 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` . - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/2jzeq1r6/) - -2. **[Optional] Add the camera list and resolution list** - - If the class names of the created select elements match the default class names, i.e. `dce-sel-camera` and `dce-sel-resolution` respectively, the SDK will automatically populate the lists and handle the camera/resolution switching. - - ```html -
-
-
-
- ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/nbj75vxu/) - - ```html -
- - -
-
-
- ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/25v08paf/) - - > By default, only 3 hard-coded resolutions (1920 x 1080, 1280 x 720,640 x 480) are populated as options. You can show a customized set of options by hardcoding them. - - ```html - - ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/tnfjks4q/) - - > Generally, you need to provide a resolution that the camera supports. However, in case a camera does not support the specified resolution, it usually uses the cloest supported resolution. As a result, the selected resolution may not be the actual resolution. In this case, add an option with the class name `dce-opt-gotResolution` (as shown above) and the SDK will automatically use it to show the **actual resolution**. - - See the section of the Explore Features guide on [UI customization]({{site.features}}customize-the-ui.html?lang=js) to learn more. - -## API Documentation - -You can check out the detailed documentation about the APIs of the SDK at -[https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/?ver=9.6.11](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/?ver=9.6.11). - -## System Requirements - -DBR requires the following features to work: - -- Secure context (HTTPS deployment) - - When deploying your application / website for production, make sure to serve it via a secure HTTPS connection. This is required for two reasons - - - Access to the camera video stream is only granted in a security context. Most browsers impose this restriction. - > Some browsers like Chrome may grant the access for `http://127.0.0.1` and `http://localhost` or even for pages opened directly from the local disk (`file:///...`). This can be helpful for temporary development and test. - - - Dynamsoft License requires a secure context to work. - -- `WebAssembly`, `Blob`, `URL`/`createObjectURL`, `Web Workers` - - The above four features are required for the SDK to work. - -- `MediaDevices`/`getUserMedia` - - This API is only required for in-browser video streaming. If a browser does not support this API, the [Single Frame Mode](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/BarcodeScanner.html?ver=9.6.11&utm_source=guide#singleframemode) will be used automatically. If the API exists but doesn't work correctly, the Single Frame Mode can be used as an alternative way to access the camera. - -- `getSettings` - - This API inspects the video input which is a `MediaStreamTrack` object about its constrainable properties. - -The following table is a list of supported browsers based on the above requirements: - - Browser Name | Version - :-: | :-: - Chrome | v59+1 - Firefox | v52+ (v55+ on Android/iOS1) - Edge2 | v16+ - Safari3 | v11+ - - 1 iOS 14.3+ is required for camera video streaming in Chrome and Firefox or Apps using webviews. - - 2 On Edge, due to strict Same-origin policy, you must host the SDK files on the same domain as your web page. - - 3 Safari v11.x already has the required features, but it has many other issues, so we recommend v12+. - -Apart from the browsers, the operating systems may impose some limitations of their own that could restrict the use of the SDK. Browser compatibility ultimately depends on whether the browser on that particular operating system supports the features listed above. - -## How to Upgrade - -If you want to upgrade the SDK from an old version to a newer one, please see [how to upgrade](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/upgrade-guide/?ver=9.6.11&utm_source=guide). - -## Release Notes - -Learn about what are included in each release at [https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/release-notes/?ver=latest](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/release-notes/?ver=latest). - -## Next Steps - -Now that you have got the SDK integrated, you can choose to move forward in the following directions - -1. Check out the [Official Samples and Demo](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/index.html?ver=latest) -2. Learn how to make use of the [SDK features](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/user-guide/explore-features/index.html?ver=latest) -3. See how the SDK works in [Popular Use Cases](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/user-guide/use-cases/index.html?ver=latest) diff --git a/programming-old/javascript/user-guide/index-v9.6.2.md b/programming-old/javascript/user-guide/index-v9.6.2.md deleted file mode 100644 index b4c138e2..00000000 --- a/programming-old/javascript/user-guide/index-v9.6.2.md +++ /dev/null @@ -1,523 +0,0 @@ ---- -layout: default-layout -title: v9.6.2 User Guide - Dynamsoft Barcode Reader JavaScript Edition -description: This is the user guide of Dynamsoft Barcode Reader JavaScript SDK. -keywords: user guide, javascript, js -breadcrumbText: User Guide -noTitleIndex: true -needGenerateH3Content: true -needAutoGenerateSidebar: true -permalink: /programming/javascript/user-guide/index-v9.6.2.html ---- - - - -# Barcode Reader for Your Website - User Guide - -[Dynamsoft Barcode Reader JavaScript Edition](https://www.dynamsoft.com/barcode-reader/sdk-javascript/) (DBR-JS) is equipped with industry-leading algorithms for exceptional speed, accuracy and read rates in barcode reading. Using its well-designed API, you can turn your web page into a barcode scanner with just a few lines of code. - -![version](https://img.shields.io/npm/v/dynamsoft-javascript-barcode.svg) -![downloads](https://img.shields.io/npm/dm/dynamsoft-javascript-barcode.svg) -![jsdelivr](https://img.shields.io/jsdelivr/npm/hm/dynamsoft-javascript-barcode.svg) -![vulnerabilities](https://img.shields.io/snyk/vulnerabilities/npm/dynamsoft-javascript-barcode.svg) - -Once the DBR-JS SDK gets integrated into your web page, your users can access a camera via the browser and read barcodes directly from its video input. - -In this guide, you will learn step by step on how to integrate the DBR-JS SDK into your website. - -Table of Contents - -- [Barcode Reader for Your Website - User Guide](#barcode-reader-for-your-website---user-guide) - - [Hello World - Simplest Implementation](#hello-world---simplest-implementation) - - [Understand the code](#understand-the-code) - - [About the code](#about-the-code) - - [Run the example](#run-the-example) - - [Building your own page](#building-your-own-page) - - [Include the SDK](#include-the-sdk) - - [Use a public CDN](#use-a-public-cdn) - - [Host the SDK yourself](#host-the-sdk-yourself) - - [Configure the SDK](#configure-the-sdk) - - [Specify the license](#specify-the-license) - - [Specify the location of the "engine" files](#specify-the-location-of-the-engine-files) - - [Interact with the SDK](#interact-with-the-sdk) - - [Create a `BarcodeScanner` object](#create-a-barcodescanner-object) - - [Customize the `BarcodeScanner` Settings (optional)](#customize-the-barcodescanner-settings-optional) - - [Customize the UI (optional)](#customize-the-ui-optional) - - [Modify the file `dist/dbr.ui.html` directly](#modify-the-file-distdbruihtml-directly) - - [Copy the file `dist/dbr.ui.html` to your application, modify it and use the the API `defaultUIElementURL` to set it as the default UI](#copy-the-file-distdbruihtml-to-your-application-modify-it-and-use-the-the-api-defaultuielementurl-to-set-it-as-the-default-ui) - - [Append the default UI element to your page, customize it before showing it](#append-the-default-ui-element-to-your-page-customize-it-before-showing-it) - - [Build the UI element from scratch and connect it to the SDK with the API setUIElement(HTMLElement)](#build-the-ui-element-from-scratch-and-connect-it-to-the-sdk-with-the-api-setuielementhtmlelement) - - [API Documentation](#api-documentation) - - [System Requirements](#system-requirements) - - [How to Upgrade](#how-to-upgrade) - - [Release Notes](#release-notes) - - [Next Steps](#next-steps) - -**Popular Examples** - -- Hello World - [Guide](#hello-world---simplest-implementation) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.2/1.hello-world/1.hello-world.html) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/1.hello-world.html?ver=9.6.2&utm_source=guide) -- Angular App - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/helloworld-angular.html?ver=9.6.2&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.2/1.hello-world/3.read-video-angular) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/3.read-video-angular/dist/hello-world/?ver=9.6.2&utm_source=guide) -- React App - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/helloworld-reactjs.html?ver=9.6.2&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.2/1.hello-world/4.read-video-react) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/4.read-video-react/build/?ver=9.6.2&utm_source=guide) -- Vue App - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/helloworld-vuejsv3.html?ver=9.6.2&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.2/1.hello-world/6.read-video-vue3) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/6.read-video-vue3/dist/?ver=9.6.2&utm_source=guide) -- PWA App - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/helloworld-pwa.html?ver=9.6.2&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.2/1.hello-world/10.read-video-pwa) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/10.read-video-pwa/helloworld-pwa.html?ver=9.6.2&utm_source=guide) -- Read Driver Licenses - [Guide](https://www.dynamsoft.com/barcode-reader/docs/core/programming/usecases/scan-and-parse-AAMVA.html?ver=9.6.2&utm_source=guide&&lang=js) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.2/4.use-case/2.read-a-drivers-license.html) \| [Run](https://demo.dynamsoft.com/samples/dbr/js/4.use-case/2.read-a-drivers-license.html?ver=9.6.2&utm_source=guide) -- Fill A Form - [Guide](https://www.dynamsoft.com/barcode-reader/docs/core/programming/usecases/scan-barcodes-as-input.html?lang=js&&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.2/4.use-case/1.fill-a-form-with-barcode-reading.html) \| [Run](https://demo.dynamsoft.com/samples/dbr/js/4.use-case/1.fill-a-form-with-barcode-reading.html?ver=9.6.2&utm_source=guide) - -You can also: - -- Try the Official Demo - [Run](https://demo.dynamsoft.com/barcode-reader-js/?ver=9.6.2&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-demo/) -- Try Online Examples - [Run](https://demo.dynamsoft.com/Samples/DBR/JS/index.html?ver=9.6.2&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/v9.6.2/) - -## Hello World - Simplest Implementation - -Let's start with the "Hello World" example of the DBR-JS SDK which demonstrates how to use the minimum code to enable a web page to read barcodes from a live video stream. - -- Basic Requirements - - Internet connection - - [A supported browser](#system-requirements) - - Camera access - -### Understand the code - -The complete code of the "Hello World" example is shown below - -```html - - - - - - - - - -``` - -

- - Code in Github - -   - - Run via JSFiddle - -   - - Run in Dynamsoft - -

- ------ - -#### About the code - -- The DBR-JS SDK is included in the code via the **jsDelivr** CDN. - -> In some rare cases, you might not be able to access the CDN. If this happens, you can use [https://download2.dynamsoft.com/dbr/dynamsoft-barcode-reader-js/dynamsoft-barcode-reader-js-9.6.2/dist/dbr.js](https://download2.dynamsoft.com/dbr/dynamsoft-barcode-reader-js/dynamsoft-barcode-reader-js-9.6.2/dist/dbr.js) for the test. However, please DO NOT use it in your production application because it is temporary. Instead, you can try [hosting the SDK yourself](#host-the-sdk-yourself). - -- `license`: This property specifies a license key. Note that the license "DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9" used in this example is an online license and requires network connection to work. Read more on [Specify the license](#specify-the-license). - -- `createInstance()`: This method creates a `BarcodeScanner` object. This object can read barcodes directly from a video input with the help of its interactive UI (hidden by default) and the MediaDevices interface. - -- `onFrameRead`: This event is triggered every time the SDK finishes scanning a video frame. The `results` object contains all the barcode results that the SDK have found on this frame. In this example, we print the results to the browser console. - -- `onUniqueRead`: This event is triggered when the SDK finds a new barcode, which is not a duplicate among multiple frames. `txt` holds the barcode text value while `result` is an object that holds details of the barcode. In this example, an alert will be displayed for this new barcode. - -- `show()`: This method brings up the built-in UI of the `BarcodeScanner` object and starts scanning. - -### Run the example - -You can run the example deployed to the Dynamsoft Demo Server or test it with JSFiddle code editor. You will be asked to allow access to your camera, after which the video will be displayed on the page. After that, you can point the camera at a barcode to read it. - -When a barcode is decoded, you will see the result text pop up and the barcode location will be highlighted in the video feed. - -Alternatively, you can make a local test simply by taking the code in step 1, pasting it in a file with the name "hello-world.html" and open it in a browser. - -*Note*: - -If you open the web page as `file:///` or `http://` , the camera may not work correctly because the API getUserMedia usually requires HTTPS to access the camera. - -To make sure your web application can access the camera, please configure your web server to support HTTPS. The following links may help. - -1. NGINX: Configuring HTTPS servers -2. IIS: Create a Self Signed Certificate in IIS -3. Tomcat: Setting Up SSL on Tomcat in 5 minutes -4. Node.js: npm tls - -If the test doesn't go as expected, you can [contact us](https://www.dynamsoft.com/contact/?ver=9.6.2&utm_source=guide). - - - -

- -**Pinned Message:** - -- [Temporary solution for iPhone 14 Pro Max rear camera not focusing](https://github.com/Dynamsoft/barcode-reader-javascript-samples/issues/99#issuecomment-1407584605) - -## Building your own page - -### Include the SDK - -#### Use a public CDN - -The simplest way to include the SDK is to use either the [jsDelivr](https://jsdelivr.com/) or [UNPKG](https://unpkg.com/) CDN. The "hello world" example above uses **jsDelivr**. - -- jsDelivr - - ```html - - ``` - -- UNPKG - - ```html - - ``` - -#### Host the SDK yourself - -Besides using the public CDN, you can also download the SDK and host its files on your own server or a commercial CDN before including it in your application. - -Options to download the SDK: - -- From the website - - Download the JavaScript Package - -- yarn - - ```cmd - yarn add dynamsoft-javascript-barcode - ``` - -- npm - - ```cmd - npm install dynamsoft-javascript-barcode --save - ``` - -Depending on how you downloaded the SDK and how you intend to use it, you can typically include it like this: - -```html - -``` - -or - -```html - -``` - -or - -```typescript -import { BarcodeScanner } from 'dynamsoft-javascript-barcode'; -``` - -**NOTE** - -* Some older web application servers do not set `.wasm` mimetype as `application/wasm`. Upgrade your web application servers, or define the mimetype yourselves: - * [Apache](https://developer.mozilla.org/en-US/docs/Learn/Server-side/Apache_Configuration_htaccess#media_types_and_character_encodings) - * [IIS](https://docs.microsoft.com/en-us/iis/configuration/system.webserver/staticcontent/mimemap) - * [Nginx](https://www.nginx.com/resources/wiki/start/topics/examples/full/#mime-types) - -* To work properly, the SDK requires a few engine files, which are relatively large and may take quite a few seconds to download. We recommend that you set a longer cache time for these engine files, to maximize the performance of your web application. - - ```cmd - Cache-Control: max-age=31536000 - ``` - - Reference: [Cache-Control](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control). - -### Configure the SDK - -Before using the SDK, you need to configure a few things. - -#### Specify the license - -The SDK requires a license to work, use the API `license` to specify a license key. - -```javascript -Dynamsoft.DBR.BarcodeScanner.license = "YOUR-LICENSE-KEY"; -``` - -To test the SDK, you can request a 30-day trial license via the Request a Trial License link. - -> If you register a Dynamsoft account and download the SDK from the official website, Dynamsoft will automatically generate a 30-day trial license for you, and put the license key into all the samples attached to the SDK. - -#### Specify the location of the "engine" files - -This is usually only required with frameworks like Angular or React, etc. where dbr.js is compiled into another file. - -The purpose is to tell the SDK where to find the engine files (\*.worker.js, \*.wasm.js and \*.wasm, etc.). The API is called `engineResourcePath`: - -```javascript -//The following code uses the jsDelivr CDN, feel free to change it to your own location of these files -Dynamsoft.DBR.BarcodeScanner.engineResourcePath = "https://cdn.jsdelivr.net/npm/dynamsoft-javascript-barcode@9.6.2/dist/"; -``` - -### Interact with the SDK - -#### Create a `BarcodeScanner` object - -You can use one of two classes ( `BarcodeScanner` and `BarcodeReader` ) to interact with the SDK. `BarcodeReader` is a low-level class that processes images directly. `BarcodeScanner` , on the other hand, inherits from `BarcodeReader` and provides high-level APIs and a built-in GUI to allow continuous barcode scanning on video frames. We'll focus on `BarcodeScanner` in this guide. - -To use the SDK, we first create a `BarcodeScanner` object. - -```javascript -Dynamsoft.DBR.BarcodeScanner.license = "YOUR-LICENSE-KEY"; -let scanner = null; -try { - scanner = await Dynamsoft.DBR.BarcodeScanner.createInstance(); -} catch (ex) { - console.error(ex); -} -``` - -Tip: When creating a `BarcodeScanner` object within a function which may be called more than once, it's best to use a "helper" variable to avoid double creation such as `pScanner` in the following code - -```javascript -Dynamsoft.DBR.BarcodeScanner.license = "YOUR-LICENSE-KEY"; -let pScanner = null; -document.getElementById('btn-scan').addEventListener('click', async () => { - try { - const scanner = await (pScanner = pScanner || Dynamsoft.DBR.BarcodeScanner.createInstance()); - } catch (ex) { - console.error(ex); - } -}); -``` - -#### Customize the `BarcodeScanner` Settings (optional) - -Let's take a look at the following code snippets: - -```javascript -// Sets which camera and what resolution to use -let allCameras = await scanner.getAllCameras(); -await scanner.setCurrentCamera(allCameras[0].deviceId); -await scanner.setResolution(1280, 720); -``` - -```javascript -// Sets up the scanner behavior -let scanSettings = await scanner.getScanSettings(); -// Disregards duplicated results found in a specified time period (in milliseconds). -scanSettings.duplicateForgetTime = 5000; // The default is 3000 -// Sets a scan interval in milliseconds so the SDK may release the CPU from time to time. -// (setting this value larger is a simple way to save battery power and reduce device heating). -scanSettings.intervalTime = 100; // The default is 0. -// Sets captureAndDecodeInParallel to false, which tells the SDK not to acquire the next frame while decoding the first. -// This is another way to save battery power and is recommended on low-end phones. However, it does slow down the decoding speed. -scanSettings.captureAndDecodeInParallel = false; // The default is true. -await scanner.updateScanSettings(scanSettings); -``` - -```javascript -// Uses one of the built-in RuntimeSetting templates: "single" (decode a single barcode, the default mode), "speed", "balance", "coverage", "dense" and "distance" -await scanner.updateRuntimeSettings("speed"); - -// Makes changes to the template. The code below demonstrates how to specify enabled symbologies -let runtimeSettings = await scanner.getRuntimeSettings(); -runtimeSettings.barcodeFormatIds = Dynamsoft.DBR.EnumBarcodeFormat.BF_ONED | Dynamsoft.DBR.EnumBarcodeFormat.BF_QR_CODE; -await scanner.updateRuntimeSettings(runtimeSettings); -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/yfkcajxz/) - -As you can see from the above code snippets, there are three types of configurations: - -- Customize the data source: This configuration includes which camera to use, the preferred resolution, etc. Learn more here. - -- `get/updateScanSettings`: Configures the behavior of the scanner which includes `duplicateForgetTime` and `intervalTime`, etc. - -- `get/updateRuntimeSettings`: Configures the decode engine with either a built-in template or a comprehensive `RuntimeSettings` object. For example, the following uses the built-in "speed" settings with updated `localizationModes`. - - ```javascript - await barcodeScanner.updateRuntimeSettings("speed"); - //await barcodeScanner.updateRuntimeSettings("balance"); //alternative - //await barcodeScanner.updateRuntimeSettings("coverage"); //alternative - let settings = await barcodeScanner.getRuntimeSettings(); - settings.localizationModes = [ - Dynamsoft.DBR.EnumLocalizationMode.LM_CONNECTED_BLOCKS, - Dynamsoft.DBR.EnumLocalizationMode.LM_SCAN_DIRECTLY, - Dynamsoft.DBR.EnumLocalizationMode.LM_LINES, 0, 0, 0, 0, 0 - ]; - await barcodeScanner.updateRuntimeSettings(settings); - ``` - - Try in [JSFiddle](https://jsfiddle.net/DynamsoftTeam/f24h8c1m/). - - See also [settings samples](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/parameter-settings.html?ver=9.6.2&utm_source=guide). - -> Find the full list of the runtime settings here. - -### Customize the UI (optional) - -The built-in UI of the `BarcodeScanner` object is defined in the file `dist/dbr.ui.html` . There are a few ways to customize it: - -#### Modify the file `dist/dbr.ui.html` directly - - This option is only possible when you [Host the SDK yourself](#host-the-sdk-yourself) instead of using a public CDN. - -#### Copy the file `dist/dbr.ui.html` to your application, modify it and use the the API `defaultUIElementURL` to set it as the default UI - - ```javascript - // This line only takes effect before the method `createInstance()` is called. - Dynamsoft.DBR.BarcodeScanner.defaultUIElementURL = "THE-URL-TO-THE-FILE"; - ``` - -#### Append the default UI element to your page, customize it before showing it - - ```html -
- ``` - - ```javascript - document.getElementById('div-ui-container').appendChild(scanner.getUIElement()); - document.getElementsByClassName('dce-btn-close')[0].hidden = true; // Hide the close button - ``` - -#### Build the UI element from scratch and connect it to the SDK with the API setUIElement(HTMLElement) - -1. **Embed the video** - - ```html -
-
-
- - ``` - - > 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` . - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/2jzeq1r6/) - -2. **[Optional] Add the camera list and resolution list** - - If the class names of the created select elements match the default class names, i.e. `dce-sel-camera` and `dce-sel-resolution` respectively, the SDK will automatically populate the lists and handle the camera/resolution switching. - - ```html -
-
-
-
- ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/nbj75vxu/) - - ```html -
- - -
-
-
- ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/25v08paf/) - - > By default, only 3 hard-coded resolutions (1920 x 1080, 1280 x 720,640 x 480) are populated as options. You can show a customized set of options by hardcoding them. - - ```html - - ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/tnfjks4q/) - - > Generally, you need to provide a resolution that the camera supports. However, in case a camera does not support the specified resolution, it usually uses the cloest supported resolution. As a result, the selected resolution may not be the actual resolution. In this case, add an option with the class name `dce-opt-gotResolution` (as shown above) and the SDK will automatically use it to show the **actual resolution**. - - See the section of the Explore Features guide on [UI customization]({{site.features}}customize-the-ui.html?lang=js) to learn more. - -## API Documentation - -You can check out the detailed documentation about the APIs of the SDK at -[https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/?ver=9.6.2](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/?ver=9.6.2). - -## System Requirements - -DBR requires the following features to work: - -- Secure context (HTTPS deployment) - - When deploying your application / website for production, make sure to serve it via a secure HTTPS connection. This is required for two reasons - - - Access to the camera video stream is only granted in a security context. Most browsers impose this restriction. - > Some browsers like Chrome may grant the access for `http://127.0.0.1` and `http://localhost` or even for pages opened directly from the local disk (`file:///...`). This can be helpful for temporary development and test. - - - Dynamsoft License requires a secure context to work. - -- `WebAssembly`, `Blob`, `URL`/`createObjectURL`, `Web Workers` - - The above four features are required for the SDK to work. - -- `MediaDevices`/`getUserMedia` - - This API is only required for in-browser video streaming. If a browser does not support this API, the [Single Frame Mode](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/BarcodeScanner.html?ver=9.6.2&utm_source=guide#singleframemode) will be used automatically. If the API exists but doesn't work correctly, the Single Frame Mode can be used as an alternative way to access the camera. - -- `getSettings` - - This API inspects the video input which is a `MediaStreamTrack` object about its constrainable properties. - -The following table is a list of supported browsers based on the above requirements: - - Browser Name | Version - :-: | :-: - Chrome | v59+1 - Firefox | v52+ (v55+ on Android/iOS1) - Edge2 | v16+ - Safari3 | v11+ - - 1 iOS 14.3+ is required for camera video streaming in Chrome and Firefox or Apps using webviews. - - 2 On Edge, due to strict Same-origin policy, you must host the SDK files on the same domain as your web page. - - 3 Safari v11.x already has the required features, but it has many other issues, so we recommend v12+. - -Apart from the browsers, the operating systems may impose some limitations of their own that could restrict the use of the SDK. Browser compatibility ultimately depends on whether the browser on that particular operating system supports the features listed above. - -## How to Upgrade - -If you want to upgrade the SDK from an old version to a newer one, please see [how to upgrade](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/upgrade-guide/?ver=9.6.2&utm_source=guide). - -## Release Notes - -Learn about what are included in each release at [https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/release-notes/?ver=latest](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/release-notes/?ver=latest). - -## Next Steps - -Now that you have got the SDK integrated, you can choose to move forward in the following directions - -1. Check out the [Official Samples and Demo](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/index.html?ver=latest) -2. Learn how to make use of the [SDK features](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/user-guide/explore-features/index.html?ver=latest) -3. See how the SDK works in [Popular Use Cases](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/user-guide/use-cases/index.html?ver=latest) diff --git a/programming-old/javascript/user-guide/index-v9.6.20.md b/programming-old/javascript/user-guide/index-v9.6.20.md deleted file mode 100644 index 291372fd..00000000 --- a/programming-old/javascript/user-guide/index-v9.6.20.md +++ /dev/null @@ -1,510 +0,0 @@ ---- -layout: default-layout -title: v9.6.20 User Guide - Dynamsoft Barcode Reader JavaScript Edition -description: This is the user guide of Dynamsoft Barcode Reader JavaScript SDK. -keywords: user guide, javascript, js -breadcrumbText: User Guide -noTitleIndex: true -needGenerateH3Content: true -needAutoGenerateSidebar: true -permalink: /programming/javascript/user-guide/index-v9.6.20.html ---- - - - -# Barcode Reader for Your Website - User Guide - -[Dynamsoft Barcode Reader JavaScript Edition](https://www.dynamsoft.com/barcode-reader/sdk-javascript/) (DBR-JS) is equipped with industry-leading algorithms for exceptional speed, accuracy and read rates in barcode reading. Using its well-designed API, you can turn your web page into a barcode scanner with just a few lines of code. - -![version](https://img.shields.io/npm/v/dynamsoft-javascript-barcode.svg) -![downloads](https://img.shields.io/npm/dm/dynamsoft-javascript-barcode.svg) -![jsdelivr](https://img.shields.io/jsdelivr/npm/hm/dynamsoft-javascript-barcode.svg) -![vulnerabilities](https://img.shields.io/snyk/vulnerabilities/npm/dynamsoft-javascript-barcode.svg) - -Once the DBR-JS SDK gets integrated into your web page, your users can access a camera via the browser and read barcodes directly from its video input. - - - -In this guide, you will learn step by step on how to integrate the DBR-JS SDK into your website. - -Table of Contents - -- [Hello World - Simplest Implementation](#hello-world---simplest-implementation) - - [Understand the code](#understand-the-code) - - [Run the example](#run-the-example) -- [Building your own page](#building-your-own-page) - - [Include the SDK](#include-the-sdk) - - [Configure the SDK](#configure-the-sdk) - - [Interact with the SDK](#interact-with-the-sdk) - - [Customize the UI (optional)](#customize-the-ui-optional) -- [API Documentation](#api-documentation) -- [System Requirements](#system-requirements) -- [How to Upgrade](#how-to-upgrade) -- [Release Notes](#release-notes) -- [Next Steps](#next-steps) - -**Popular Examples** - -- Hello World - [Guide](#hello-world---simplest-implementation) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.20/1.hello-world/1.hello-world.html) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/1.hello-world.html?ver=9.6.20&utm_source=guide) -- Angular App - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/helloworld-angular.html?ver=9.6.20&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.20/1.hello-world/3.read-video-angular) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/3.read-video-angular/dist/hello-world/?ver=9.6.20&utm_source=guide) -- React App - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/helloworld-reactjs.html?ver=9.6.20&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.20/1.hello-world/4.read-video-react) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/4.read-video-react/build/?ver=9.6.20&utm_source=guide) -- Vue App - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/helloworld-vuejsv3.html?ver=9.6.20&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.20/1.hello-world/6.read-video-vue3) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/6.read-video-vue3/dist/?ver=9.6.20&utm_source=guide) -- PWA App - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/helloworld-pwa.html?ver=9.6.20&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.20/1.hello-world/10.read-video-pwa) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/10.read-video-pwa/helloworld-pwa.html?ver=9.6.20&utm_source=guide) -- WebView in Android and iOS - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/v9.6.20/1.hello-world/14.read-video-webview) -- Read Driver Licenses - [Guide](https://www.dynamsoft.com/barcode-reader/docs/core/programming/usecases/scan-and-parse-AAMVA.html?ver=9.6.20&utm_source=guide&&lang=js) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.20/4.use-case/2.read-a-drivers-license.html) \| [Run](https://demo.dynamsoft.com/samples/dbr/js/4.use-case/2.read-a-drivers-license.html?ver=9.6.20&utm_source=guide) -- Fill A Form - [Guide](https://www.dynamsoft.com/barcode-reader/docs/core/programming/usecases/scan-barcodes-as-input.html?lang=js&&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.20/4.use-case/1.fill-a-form-with-barcode-reading.html) \| [Run](https://demo.dynamsoft.com/samples/dbr/js/4.use-case/1.fill-a-form-with-barcode-reading.html?ver=9.6.20&utm_source=guide) -- Show result information on the video - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/main/4.use-case/3.show-result-texts-on-the-video.html) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/4.use-case/3.show-result-texts-on-the-video.html?ver=9.6.20&utm_source=guide) -- Debug Camera and Collect Video Frame - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/debug.html?lang=js&&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.20/5.others/debug) - -You can also: - -- Try the Official Demo - [Run](https://demo.dynamsoft.com/barcode-reader-js/?ver=9.6.20&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-demo/) -- Try Online Examples - [Run](https://demo.dynamsoft.com/Samples/DBR/JS/index.html?ver=9.6.20&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/v9.6.20/) - -## Hello World - Simplest Implementation - -Let's start with the "Hello World" example of the DBR-JS SDK which demonstrates how to use the minimum code to enable a web page to read barcodes from a live video stream. - -- Basic Requirements - - Internet connection - - [A supported browser](#system-requirements) - - Camera access - -### Understand the code - -The complete code of the "Hello World" example is shown below - -```html - - - - - - - - - -``` - -

- - Code in Github - -   - - Run via JSFiddle - -   - - Run in Dynamsoft - -

- ------ - -#### About the code - -- The DBR-JS SDK is included in the code via the **jsDelivr** CDN. - -> In some rare cases, you might not be able to access the CDN. If this happens, you can use [https://download2.dynamsoft.com/dbr/dynamsoft-barcode-reader-js/dynamsoft-barcode-reader-js-9.6.20/dist/dbr.js](https://download2.dynamsoft.com/dbr/dynamsoft-barcode-reader-js/dynamsoft-barcode-reader-js-9.6.20/dist/dbr.js) for the test. However, please DO NOT use CDN of `download2.dynamsoft.com` in your production application because it is temporary. Instead, you can try [hosting the SDK yourself](#host-the-sdk-yourself). - -- `license`: This property specifies a license key. Note that the license "DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9" used in this example is an online license and requires network connection to work. Read more on [Specify the license](#specify-the-license). - -- `createInstance()`: This method creates a `BarcodeScanner` object. This object can read barcodes directly from a video input with the help of its interactive UI (hidden by default) and the MediaDevices interface. - -- `onFrameRead`: This event is triggered every time the SDK finishes scanning a video frame. The `results` object contains all the barcode results that the SDK have found on this frame. In this example, we print the results to the browser console. - -- `onUniqueRead`: This event is triggered when the SDK finds a new barcode, which is not a duplicate among multiple frames. `txt` holds the barcode text value while `result` is an object that holds details of the barcode. In this example, an alert will be displayed for this new barcode. - -- `show()`: This method brings up the built-in UI of the `BarcodeScanner` object and starts scanning. - -### Run the example - -You can run the example deployed to the Dynamsoft Demo Server or test it with JSFiddle code editor. You will be asked to allow access to your camera, after which the video will be displayed on the page. After that, you can point the camera at a barcode to read it. - -When a barcode is decoded, you will see the result text pop up and the barcode location will be highlighted in the video feed. - -Alternatively, you can make a local test simply by taking the code in step 1, pasting it in a file with the name "hello-world.html" and open it in a browser. - -*Note*: - -If you open the web page as `file:///` or `http://` , the camera may not work correctly because the API getUserMedia usually requires HTTPS to access the camera. - -To make sure your web application can access the camera, please configure your web server to support HTTPS. The following links may help. - -1. NGINX: Configuring HTTPS servers -2. IIS: Create a Self Signed Certificate in IIS -3. Tomcat: Setting Up SSL on Tomcat in 5 minutes -4. Node.js: npm tls - -If the test doesn't go as expected, you can [contact us](https://www.dynamsoft.com/contact/?ver=9.6.20&utm_source=guide). - -## Building your own page - -### Include the SDK - -#### Use a public CDN - -The simplest way to include the SDK is to use either the [jsDelivr](https://jsdelivr.com/) or [UNPKG](https://unpkg.com/) CDN. The "hello world" example above uses **jsDelivr**. - -- jsDelivr - - ```html - - ``` - -- UNPKG - - ```html - - ``` - -#### Host the SDK yourself - -Besides using the public CDN, you can also download the SDK and host its files on your own server or a commercial CDN before including it in your application. - -Options to download the SDK: - -- From the website - - Download the JavaScript Package - -- yarn - - ```cmd - yarn add dynamsoft-javascript-barcode - ``` - -- npm - - ```cmd - npm install dynamsoft-javascript-barcode --save - ``` - -Depending on how you downloaded the SDK and how you intend to use it, you can typically include it like this: - -```html - -``` - -or - -```html - -``` - -or - -```typescript -import { BarcodeScanner } from 'dynamsoft-javascript-barcode'; -``` - -**NOTE** - -* Some older web application servers do not set `.wasm` mimetype as `application/wasm`. Upgrade your web application servers, or define the mimetype yourselves: - * [Apache](https://developer.mozilla.org/en-US/docs/Learn/Server-side/Apache_Configuration_htaccess#media_types_and_character_encodings) - * [IIS](https://docs.microsoft.com/en-us/iis/configuration/system.webserver/staticcontent/mimemap) - * [Nginx](https://www.nginx.com/resources/wiki/start/topics/examples/full/#mime-types) - -* To work properly, the SDK requires a few engine files, which are relatively large and may take quite a few seconds to download. We recommend that you set a longer cache time for these engine files, to maximize the performance of your web application. - - ```cmd - Cache-Control: max-age=31536000 - ``` - - Reference: [Cache-Control](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control). - -### Configure the SDK - -Before using the SDK, you need to configure a few things. - -#### Specify the license - -The SDK requires a license to work, use the API `license` to specify a license key. - -```javascript -Dynamsoft.DBR.BarcodeScanner.license = "YOUR-LICENSE-KEY"; -``` - -To test the SDK, you can request a 30-day trial license via the Request a Trial License link. - -> If you register a Dynamsoft account and download the SDK from the official website, Dynamsoft will automatically generate a 30-day trial license for you, and put the license key into all the samples attached to the SDK. - -#### Specify the location of the "engine" files - -This is usually only required with frameworks like Angular or React, etc. where dbr.js is compiled into another file. - -The purpose is to tell the SDK where to find the engine files (\*.worker.js, \*.wasm.js and \*.wasm, etc.). The API is called `engineResourcePath`: - -```javascript -//The following code uses the jsDelivr CDN, feel free to change it to your own location of these files -Dynamsoft.DBR.BarcodeScanner.engineResourcePath = "https://cdn.jsdelivr.net/npm/dynamsoft-javascript-barcode@9.6.20/dist/"; -``` - -### Interact with the SDK - -#### Create a `BarcodeScanner` object - -You can use one of two classes ( `BarcodeScanner` and `BarcodeReader` ) to interact with the SDK. `BarcodeReader` is a low-level class that processes images directly. `BarcodeScanner` , on the other hand, inherits from `BarcodeReader` and provides high-level APIs and a built-in GUI to allow continuous barcode scanning on video frames. We'll focus on `BarcodeScanner` in this guide. - -To use the SDK, we first create a `BarcodeScanner` object. - -```javascript -Dynamsoft.DBR.BarcodeScanner.license = "YOUR-LICENSE-KEY"; -let scanner = null; -try { - scanner = await Dynamsoft.DBR.BarcodeScanner.createInstance(); -} catch (ex) { - console.error(ex); -} -``` - -Tip: When creating a `BarcodeScanner` object within a function which may be called more than once, it's best to use a "helper" variable to avoid double creation such as `pScanner` in the following code - -```javascript -Dynamsoft.DBR.BarcodeScanner.license = "YOUR-LICENSE-KEY"; -let pScanner = null; -document.getElementById('btn-scan').addEventListener('click', async () => { - try { - const scanner = await (pScanner = pScanner || Dynamsoft.DBR.BarcodeScanner.createInstance()); - } catch (ex) { - console.error(ex); - } -}); -``` - -#### Customize the `BarcodeScanner` Settings (optional) - -Let's take a look at the following code snippets: - -```javascript -// Sets which camera and what resolution to use -let allCameras = await scanner.getAllCameras(); -await scanner.setCurrentCamera(allCameras[0].deviceId); -await scanner.setResolution(1280, 720); -``` - -```javascript -// Sets up the scanner behavior -let scanSettings = await scanner.getScanSettings(); -// Disregards duplicated results found in a specified time period (in milliseconds). -scanSettings.duplicateForgetTime = 5000; // The default is 3000 -// Sets a scan interval in milliseconds so the SDK may release the CPU from time to time. -// (setting this value larger is a simple way to save battery power and reduce device heating). -scanSettings.intervalTime = 100; // The default is 0. -// Sets captureAndDecodeInParallel to false, which tells the SDK not to acquire the next frame while decoding the first. -// This is another way to save battery power and is recommended on low-end phones. However, it does slow down the decoding speed. -scanSettings.captureAndDecodeInParallel = false; // The default is true. -await scanner.updateScanSettings(scanSettings); -``` - -```javascript -// Uses one of the built-in RuntimeSetting templates: "single" (decode a single barcode, the default mode), "speed", "balance", "coverage", "dense" and "distance" -await scanner.updateRuntimeSettings("speed"); - -// Makes changes to the template. The code below demonstrates how to specify enabled symbologies -let runtimeSettings = await scanner.getRuntimeSettings(); -runtimeSettings.barcodeFormatIds = Dynamsoft.DBR.EnumBarcodeFormat.BF_ONED | Dynamsoft.DBR.EnumBarcodeFormat.BF_QR_CODE; -await scanner.updateRuntimeSettings(runtimeSettings); -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/yfkcajxz/) - -As you can see from the above code snippets, there are three types of configurations: - -- Customize the data source: This configuration includes which camera to use, the preferred resolution, etc. Learn more here. - -- `get/updateScanSettings`: Configures the behavior of the scanner which includes `duplicateForgetTime` and `intervalTime`, etc. - -- `get/updateRuntimeSettings`: Configures the decode engine with either a built-in template or a comprehensive `RuntimeSettings` object. For example, the following uses the built-in "speed" settings with updated `localizationModes`. - - ```javascript - await barcodeScanner.updateRuntimeSettings("speed"); - //await barcodeScanner.updateRuntimeSettings("balance"); //alternative - //await barcodeScanner.updateRuntimeSettings("coverage"); //alternative - let settings = await barcodeScanner.getRuntimeSettings(); - settings.localizationModes = [ - Dynamsoft.DBR.EnumLocalizationMode.LM_CONNECTED_BLOCKS, - Dynamsoft.DBR.EnumLocalizationMode.LM_SCAN_DIRECTLY, - Dynamsoft.DBR.EnumLocalizationMode.LM_LINES, 0, 0, 0, 0, 0 - ]; - await barcodeScanner.updateRuntimeSettings(settings); - ``` - - Try in [JSFiddle](https://jsfiddle.net/DynamsoftTeam/f24h8c1m/). - - See also [settings samples](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/parameter-settings.html?ver=9.6.20&utm_source=guide). - -> Find the full list of the runtime settings here. - -### Customize the UI (optional) - -The built-in UI of the `BarcodeScanner` object is defined in the file `dist/dbr.ui.html` . There are a few ways to customize it: - -#### Modify the file `dist/dbr.ui.html` directly - - This option is only possible when you [Host the SDK yourself](#host-the-sdk-yourself) instead of using a public CDN. - -#### Copy the file `dist/dbr.ui.html` to your application, modify it and use the the API `defaultUIElementURL` to set it as the default UI - - ```javascript - // This line only takes effect before the method `createInstance()` is called. - Dynamsoft.DBR.BarcodeScanner.defaultUIElementURL = "THE-URL-TO-THE-FILE"; - ``` - -#### Append the default UI element to your page, customize it before showing it - - ```html -
- ``` - - ```javascript - document.getElementById('div-ui-container').appendChild(scanner.getUIElement()); - document.getElementsByClassName('dce-btn-close')[0].hidden = true; // Hide the close button - ``` - -#### Build the UI element from scratch and connect it to the SDK with the API `setUIElement(HTMLElement)` - -1. **Embed the video** - - ```html -
-
-
- - ``` - - > 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` . - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/2jzeq1r6/) - -2. **[Optional] Add the camera list and resolution list** - - If the class names of the created select elements match the default class names, i.e. `dce-sel-camera` and `dce-sel-resolution` respectively, the SDK will automatically populate the lists and handle the camera/resolution switching. - - ```html -
-
-
-
- ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/nbj75vxu/) - - ```html -
- - -
-
-
- ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/25v08paf/) - - > By default, only 3 hard-coded resolutions (1920 x 1080, 1280 x 720,640 x 480) are populated as options. You can show a customized set of options by hardcoding them. - - ```html - - ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/tnfjks4q/) - - > Generally, you need to provide a resolution that the camera supports. However, in case a camera does not support the specified resolution, it usually uses the cloest supported resolution. As a result, the selected resolution may not be the actual resolution. In this case, add an option with the class name `dce-opt-gotResolution` (as shown above) and the SDK will automatically use it to show the **actual resolution**. - - See the section of the Explore Features guide on [UI customization]({{site.features}}customize-the-ui.html?lang=js) to learn more. - -## API Documentation - -You can check out the detailed documentation about the APIs of the SDK at -[https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/?ver=9.6.20](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/?ver=9.6.20). - -## System Requirements - -DBR requires the following features to work: - -- Secure context (HTTPS deployment) - - When deploying your application / website for production, make sure to serve it via a secure HTTPS connection. This is required for two reasons - - - Access to the camera video stream is only granted in a security context. Most browsers impose this restriction. - > Some browsers like Chrome may grant the access for `http://127.0.0.1` and `http://localhost` or even for pages opened directly from the local disk (`file:///...`). This can be helpful for temporary development and test. - - - Dynamsoft License requires a secure context to work. - -- `WebAssembly`, `Blob`, `URL`/`createObjectURL`, `Web Workers` - - The above four features are required for the SDK to work. - -- `MediaDevices`/`getUserMedia` - - This API is only required for in-browser video streaming. If a browser does not support this API, the [Single Frame Mode](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/BarcodeScanner.html?ver=9.6.20&utm_source=guide#singleframemode) will be used automatically. If the API exists but doesn't work correctly, the Single Frame Mode can be used as an alternative way to access the camera. - -- `getSettings` - - This API inspects the video input which is a `MediaStreamTrack` object about its constrainable properties. - -The following table is a list of supported browsers based on the above requirements: - - Browser Name | Version - :-: | :-: - Chrome | v59+1 - Firefox | v52+ (v55+ on Android/iOS1) - Edge2 | v16+ - Safari3 | v11+ - - 1 iOS 14.3+ is required for camera video streaming in Chrome and Firefox or Apps using webviews. - - 2 On Edge, due to strict Same-origin policy, you must host the SDK files on the same domain as your web page. - - 3 Safari v11.x already has the required features, but it has many other issues, so we recommend v12+. - -Apart from the browsers, the operating systems may impose some limitations of their own that could restrict the use of the SDK. Browser compatibility ultimately depends on whether the browser on that particular operating system supports the features listed above. - -## How to Upgrade - -If you want to upgrade the SDK from an old version to a newer one, please see [how to upgrade](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/upgrade-guide/?ver=9.6.20&utm_source=guide). - -## Release Notes - -Learn about what are included in each release at [https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/release-notes/?ver=latest](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/release-notes/?ver=latest). - -## Next Steps - -Now that you have got the SDK integrated, you can choose to move forward in the following directions - -1. Check out the [Official Samples and Demo](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/index.html?ver=latest) -2. Learn how to make use of the [SDK features](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/user-guide/explore-features/index.html?ver=latest) -3. See how the SDK works in [Popular Use Cases](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/user-guide/use-cases/index.html?ver=latest) diff --git a/programming-old/javascript/user-guide/index-v9.6.21.md b/programming-old/javascript/user-guide/index-v9.6.21.md deleted file mode 100644 index 9af34089..00000000 --- a/programming-old/javascript/user-guide/index-v9.6.21.md +++ /dev/null @@ -1,511 +0,0 @@ ---- -layout: default-layout -title: v9.6.21 User Guide - Dynamsoft Barcode Reader JavaScript Edition -description: This is the user guide of Dynamsoft Barcode Reader JavaScript SDK. -keywords: user guide, javascript, js -breadcrumbText: User Guide -noTitleIndex: true -needGenerateH3Content: true -needAutoGenerateSidebar: true -permalink: /programming/javascript/user-guide/index-v9.6.21.html -schema: schemas/dynamsoft-facilitates-mit-research-schema.json ---- - - - -# Barcode Reader for Your Website - User Guide - -[Dynamsoft Barcode Reader JavaScript Edition](https://www.dynamsoft.com/barcode-reader/sdk-javascript/) (DBR-JS) is equipped with industry-leading algorithms for exceptional speed, accuracy and read rates in barcode reading. Using its well-designed API, you can turn your web page into a barcode scanner with just a few lines of code. - -![version](https://img.shields.io/npm/v/dynamsoft-javascript-barcode.svg) -![downloads](https://img.shields.io/npm/dm/dynamsoft-javascript-barcode.svg) -![jsdelivr](https://img.shields.io/jsdelivr/npm/hm/dynamsoft-javascript-barcode.svg) -![vulnerabilities](https://img.shields.io/snyk/vulnerabilities/npm/dynamsoft-javascript-barcode.svg) - -Once the DBR-JS SDK gets integrated into your web page, your users can access a camera via the browser and read barcodes directly from its video input. - - - -In this guide, you will learn step by step on how to integrate the DBR-JS SDK into your website. - -Table of Contents - -- [Hello World - Simplest Implementation](#hello-world---simplest-implementation) - - [Understand the code](#understand-the-code) - - [Run the example](#run-the-example) -- [Building your own page](#building-your-own-page) - - [Include the SDK](#include-the-sdk) - - [Configure the SDK](#configure-the-sdk) - - [Interact with the SDK](#interact-with-the-sdk) - - [Customize the UI (optional)](#customize-the-ui-optional) -- [API Documentation](#api-documentation) -- [System Requirements](#system-requirements) -- [How to Upgrade](#how-to-upgrade) -- [Release Notes](#release-notes) -- [Next Steps](#next-steps) - -**Popular Examples** - -- Hello World - [Guide](#hello-world---simplest-implementation) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.21/1.hello-world/1.hello-world.html) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/1.hello-world.html?ver=9.6.21&utm_source=guide) -- Angular App - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/helloworld-angular.html?ver=9.6.21&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.21/1.hello-world/3.read-video-angular) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/3.read-video-angular/dist/hello-world/?ver=9.6.21&utm_source=guide) -- React App - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/helloworld-reactjs.html?ver=9.6.21&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.21/1.hello-world/4.read-video-react) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/4.read-video-react/build/?ver=9.6.21&utm_source=guide) -- Vue App - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/helloworld-vuejsv3.html?ver=9.6.21&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.21/1.hello-world/6.read-video-vue3) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/6.read-video-vue3/dist/?ver=9.6.21&utm_source=guide) -- PWA App - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/helloworld-pwa.html?ver=9.6.21&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.21/1.hello-world/10.read-video-pwa) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/10.read-video-pwa/helloworld-pwa.html?ver=9.6.21&utm_source=guide) -- WebView in Android and iOS - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/v9.6.21/1.hello-world/14.read-video-webview) -- Read Driver Licenses - [Guide](https://www.dynamsoft.com/barcode-reader/docs/core/programming/usecases/scan-and-parse-AAMVA.html?ver=9.6.21&utm_source=guide&&lang=js) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.21/4.use-case/2.read-a-drivers-license.html) \| [Run](https://demo.dynamsoft.com/samples/dbr/js/4.use-case/2.read-a-drivers-license.html?ver=9.6.21&utm_source=guide) -- Fill A Form - [Guide](https://www.dynamsoft.com/barcode-reader/docs/core/programming/usecases/scan-barcodes-as-input.html?lang=js&&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.21/4.use-case/1.fill-a-form-with-barcode-reading.html) \| [Run](https://demo.dynamsoft.com/samples/dbr/js/4.use-case/1.fill-a-form-with-barcode-reading.html?ver=9.6.21&utm_source=guide) -- Show result information on the video - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/main/4.use-case/3.show-result-texts-on-the-video.html) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/4.use-case/3.show-result-texts-on-the-video.html?ver=9.6.21&utm_source=guide) -- Debug Camera and Collect Video Frame - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/debug.html?lang=js&&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.21/5.others/debug) - -You can also: - -- Try the Official Demo - [Run](https://demo.dynamsoft.com/barcode-reader-js/?ver=9.6.21&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-demo/) -- Try Online Examples - [Run](https://demo.dynamsoft.com/Samples/DBR/JS/index.html?ver=9.6.21&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/v9.6.21/) - -## Hello World - Simplest Implementation - -Let's start with the "Hello World" example of the DBR-JS SDK which demonstrates how to use the minimum code to enable a web page to read barcodes from a live video stream. - -- Basic Requirements - - Internet connection - - [A supported browser](#system-requirements) - - Camera access - -### Understand the code - -The complete code of the "Hello World" example is shown below - -```html - - - - - - - - - -``` - -

- - Code in Github - -   - - Run via JSFiddle - -   - - Run in Dynamsoft - -

- ------ - -#### About the code - -- The DBR-JS SDK is included in the code via the **jsDelivr** CDN. - -> In some rare cases, you might not be able to access the CDN. If this happens, you can use [https://download2.dynamsoft.com/dbr/dynamsoft-barcode-reader-js/dynamsoft-barcode-reader-js-9.6.21/dist/dbr.js](https://download2.dynamsoft.com/dbr/dynamsoft-barcode-reader-js/dynamsoft-barcode-reader-js-9.6.21/dist/dbr.js) for the test. However, please DO NOT use CDN of `download2.dynamsoft.com` in your production application because it is temporary. Instead, you can try [hosting the SDK yourself](#host-the-sdk-yourself). - -- `license`: This property specifies a license key. Note that the license "DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9" used in this example is an online license and requires network connection to work. Read more on [Specify the license](#specify-the-license). - -- `createInstance()`: This method creates a `BarcodeScanner` object. This object can read barcodes directly from a video input with the help of its interactive UI (hidden by default) and the MediaDevices interface. - -- `onFrameRead`: This event is triggered every time the SDK finishes scanning a video frame. The `results` object contains all the barcode results that the SDK have found on this frame. In this example, we print the results to the browser console. - -- `onUniqueRead`: This event is triggered when the SDK finds a new barcode, which is not a duplicate among multiple frames. `txt` holds the barcode text value while `result` is an object that holds details of the barcode. In this example, an alert will be displayed for this new barcode. - -- `show()`: This method brings up the built-in UI of the `BarcodeScanner` object and starts scanning. - -### Run the example - -You can run the example deployed to the Dynamsoft Demo Server or test it with JSFiddle code editor. You will be asked to allow access to your camera, after which the video will be displayed on the page. After that, you can point the camera at a barcode to read it. - -When a barcode is decoded, you will see the result text pop up and the barcode location will be highlighted in the video feed. - -Alternatively, you can make a local test simply by taking the code in step 1, pasting it in a file with the name "hello-world.html" and open it in a browser. - -*Note*: - -If you open the web page as `file:///` or `http://` , the camera may not work correctly because the API getUserMedia usually requires HTTPS to access the camera. - -To make sure your web application can access the camera, please configure your web server to support HTTPS. The following links may help. - -1. NGINX: Configuring HTTPS servers -2. IIS: Create a Self Signed Certificate in IIS -3. Tomcat: Setting Up SSL on Tomcat in 5 minutes -4. Node.js: npm tls - -If the test doesn't go as expected, you can [contact us](https://www.dynamsoft.com/contact/?ver=9.6.21&utm_source=guide). - -## Building your own page - -### Include the SDK - -#### Use a public CDN - -The simplest way to include the SDK is to use either the [jsDelivr](https://jsdelivr.com/) or [UNPKG](https://unpkg.com/) CDN. The "hello world" example above uses **jsDelivr**. - -- jsDelivr - - ```html - - ``` - -- UNPKG - - ```html - - ``` - -#### Host the SDK yourself - -Besides using the public CDN, you can also download the SDK and host its files on your own server or a commercial CDN before including it in your application. - -Options to download the SDK: - -- From the website - - Download the JavaScript Package - -- yarn - - ```cmd - yarn add dynamsoft-javascript-barcode - ``` - -- npm - - ```cmd - npm install dynamsoft-javascript-barcode --save - ``` - -Depending on how you downloaded the SDK and how you intend to use it, you can typically include it like this: - -```html - -``` - -or - -```html - -``` - -or - -```typescript -import { BarcodeScanner } from 'dynamsoft-javascript-barcode'; -``` - -**NOTE** - -* Some older web application servers do not set `.wasm` mimetype as `application/wasm`. Upgrade your web application servers, or define the mimetype yourselves: - * [Apache](https://developer.mozilla.org/en-US/docs/Learn/Server-side/Apache_Configuration_htaccess#media_types_and_character_encodings) - * [IIS](https://docs.microsoft.com/en-us/iis/configuration/system.webserver/staticcontent/mimemap) - * [Nginx](https://www.nginx.com/resources/wiki/start/topics/examples/full/#mime-types) - -* To work properly, the SDK requires a few engine files, which are relatively large and may take quite a few seconds to download. We recommend that you set a longer cache time for these engine files, to maximize the performance of your web application. - - ```cmd - Cache-Control: max-age=31536000 - ``` - - Reference: [Cache-Control](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control). - -### Configure the SDK - -Before using the SDK, you need to configure a few things. - -#### Specify the license - -The SDK requires a license to work, use the API `license` to specify a license key. - -```javascript -Dynamsoft.DBR.BarcodeScanner.license = "YOUR-LICENSE-KEY"; -``` - -To test the SDK, you can request a 30-day trial license via the Request a Trial License link. - -> If you register a Dynamsoft account and download the SDK from the official website, Dynamsoft will automatically generate a 30-day trial license for you, and put the license key into all the samples attached to the SDK. - -#### Specify the location of the "engine" files - -This is usually only required with frameworks like Angular or React, etc. where dbr.js is compiled into another file. - -The purpose is to tell the SDK where to find the engine files (\*.worker.js, \*.wasm.js and \*.wasm, etc.). The API is called `engineResourcePath`: - -```javascript -//The following code uses the jsDelivr CDN, feel free to change it to your own location of these files -Dynamsoft.DBR.BarcodeScanner.engineResourcePath = "https://cdn.jsdelivr.net/npm/dynamsoft-javascript-barcode@9.6.21/dist/"; -``` - -### Interact with the SDK - -#### Create a `BarcodeScanner` object - -You can use one of two classes ( `BarcodeScanner` and `BarcodeReader` ) to interact with the SDK. `BarcodeReader` is a low-level class that processes images directly. `BarcodeScanner` , on the other hand, inherits from `BarcodeReader` and provides high-level APIs and a built-in GUI to allow continuous barcode scanning on video frames. We'll focus on `BarcodeScanner` in this guide. - -To use the SDK, we first create a `BarcodeScanner` object. - -```javascript -Dynamsoft.DBR.BarcodeScanner.license = "YOUR-LICENSE-KEY"; -let scanner = null; -try { - scanner = await Dynamsoft.DBR.BarcodeScanner.createInstance(); -} catch (ex) { - console.error(ex); -} -``` - -Tip: When creating a `BarcodeScanner` object within a function which may be called more than once, it's best to use a "helper" variable to avoid double creation such as `pScanner` in the following code - -```javascript -Dynamsoft.DBR.BarcodeScanner.license = "YOUR-LICENSE-KEY"; -let pScanner = null; -document.getElementById('btn-scan').addEventListener('click', async () => { - try { - const scanner = await (pScanner = pScanner || Dynamsoft.DBR.BarcodeScanner.createInstance()); - } catch (ex) { - console.error(ex); - } -}); -``` - -#### Customize the `BarcodeScanner` Settings (optional) - -Let's take a look at the following code snippets: - -```javascript -// Sets which camera and what resolution to use -let allCameras = await scanner.getAllCameras(); -await scanner.setCurrentCamera(allCameras[0].deviceId); -await scanner.setResolution(1280, 720); -``` - -```javascript -// Sets up the scanner behavior -let scanSettings = await scanner.getScanSettings(); -// Disregards duplicated results found in a specified time period (in milliseconds). -scanSettings.duplicateForgetTime = 5000; // The default is 3000 -// Sets a scan interval in milliseconds so the SDK may release the CPU from time to time. -// (setting this value larger is a simple way to save battery power and reduce device heating). -scanSettings.intervalTime = 100; // The default is 0. -// Sets captureAndDecodeInParallel to false, which tells the SDK not to acquire the next frame while decoding the first. -// This is another way to save battery power and is recommended on low-end phones. However, it does slow down the decoding speed. -scanSettings.captureAndDecodeInParallel = false; // The default is true. -await scanner.updateScanSettings(scanSettings); -``` - -```javascript -// Uses one of the built-in RuntimeSetting templates: "single" (decode a single barcode, the default mode), "speed", "balance", "coverage", "dense" and "distance" -await scanner.updateRuntimeSettings("speed"); - -// Makes changes to the template. The code below demonstrates how to specify enabled symbologies -let runtimeSettings = await scanner.getRuntimeSettings(); -runtimeSettings.barcodeFormatIds = Dynamsoft.DBR.EnumBarcodeFormat.BF_ONED | Dynamsoft.DBR.EnumBarcodeFormat.BF_QR_CODE; -await scanner.updateRuntimeSettings(runtimeSettings); -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/yfkcajxz/) - -As you can see from the above code snippets, there are three types of configurations: - -- Customize the data source: This configuration includes which camera to use, the preferred resolution, etc. Learn more here. - -- `get/updateScanSettings`: Configures the behavior of the scanner which includes `duplicateForgetTime` and `intervalTime`, etc. - -- `get/updateRuntimeSettings`: Configures the decode engine with either a built-in template or a comprehensive `RuntimeSettings` object. For example, the following uses the built-in "speed" settings with updated `localizationModes`. - - ```javascript - await barcodeScanner.updateRuntimeSettings("speed"); - //await barcodeScanner.updateRuntimeSettings("balance"); //alternative - //await barcodeScanner.updateRuntimeSettings("coverage"); //alternative - let settings = await barcodeScanner.getRuntimeSettings(); - settings.localizationModes = [ - Dynamsoft.DBR.EnumLocalizationMode.LM_CONNECTED_BLOCKS, - Dynamsoft.DBR.EnumLocalizationMode.LM_SCAN_DIRECTLY, - Dynamsoft.DBR.EnumLocalizationMode.LM_LINES, 0, 0, 0, 0, 0 - ]; - await barcodeScanner.updateRuntimeSettings(settings); - ``` - - Try in [JSFiddle](https://jsfiddle.net/DynamsoftTeam/f24h8c1m/). - - See also [settings samples](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/parameter-settings.html?ver=9.6.21&utm_source=guide). - -> Find the full list of the runtime settings here. - -### Customize the UI (optional) - -The built-in UI of the `BarcodeScanner` object is defined in the file `dist/dbr.ui.html` . There are a few ways to customize it: - -#### Modify the file `dist/dbr.ui.html` directly - - This option is only possible when you [Host the SDK yourself](#host-the-sdk-yourself) instead of using a public CDN. - -#### Copy the file `dist/dbr.ui.html` to your application, modify it and use the the API `defaultUIElementURL` to set it as the default UI - - ```javascript - // This line only takes effect before the method `createInstance()` is called. - Dynamsoft.DBR.BarcodeScanner.defaultUIElementURL = "THE-URL-TO-THE-FILE"; - ``` - -#### Append the default UI element to your page, customize it before showing it - - ```html -
- ``` - - ```javascript - document.getElementById('div-ui-container').appendChild(scanner.getUIElement()); - document.getElementsByClassName('dce-btn-close')[0].hidden = true; // Hide the close button - ``` - -#### Build the UI element from scratch and connect it to the SDK with the API `setUIElement(HTMLElement)` - -1. **Embed the video** - - ```html -
-
-
- - ``` - - > 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` . - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/2jzeq1r6/) - -2. **[Optional] Add the camera list and resolution list** - - If the class names of the created select elements match the default class names, i.e. `dce-sel-camera` and `dce-sel-resolution` respectively, the SDK will automatically populate the lists and handle the camera/resolution switching. - - ```html -
-
-
-
- ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/nbj75vxu/) - - ```html -
- - -
-
-
- ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/25v08paf/) - - > By default, only 3 hard-coded resolutions (1920 x 1080, 1280 x 720,640 x 480) are populated as options. You can show a customized set of options by hardcoding them. - - ```html - - ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/tnfjks4q/) - - > Generally, you need to provide a resolution that the camera supports. However, in case a camera does not support the specified resolution, it usually uses the closest supported resolution. As a result, the selected resolution may not be the actual resolution. In this case, add an option with the class name `dce-opt-gotResolution` (as shown above) and the SDK will automatically use it to show the **actual resolution**. - - See the section of the Explore Features guide on [UI customization]({{site.features}}customize-the-ui.html?lang=js) to learn more. - -## API Documentation - -You can check out the detailed documentation about the APIs of the SDK at -[https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/?ver=9.6.21](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/?ver=9.6.21). - -## System Requirements - -DBR requires the following features to work: - -- Secure context (HTTPS deployment) - - When deploying your application / website for production, make sure to serve it via a secure HTTPS connection. This is required for two reasons - - - Access to the camera video stream is only granted in a security context. Most browsers impose this restriction. - > Some browsers like Chrome may grant the access for `http://127.0.0.1` and `http://localhost` or even for pages opened directly from the local disk (`file:///...`). This can be helpful for temporary development and test. - - - Dynamsoft License requires a secure context to work. - -- `WebAssembly`, `Blob`, `URL`/`createObjectURL`, `Web Workers` - - The above four features are required for the SDK to work. - -- `MediaDevices`/`getUserMedia` - - This API is only required for in-browser video streaming. If a browser does not support this API, the [Single Frame Mode](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/BarcodeScanner.html?ver=9.6.21&utm_source=guide#singleframemode) will be used automatically. If the API exists but doesn't work correctly, the Single Frame Mode can be used as an alternative way to access the camera. - -- `getSettings` - - This API inspects the video input which is a `MediaStreamTrack` object about its constrainable properties. - -The following table is a list of supported browsers based on the above requirements: - - Browser Name | Version - :-: | :-: - Chrome | v59+1 - Firefox | v52+ (v55+ on Android/iOS1) - Edge2 | v16+ - Safari3 | v11+ - - 1 iOS 14.3+ is required for camera video streaming in Chrome and Firefox or Apps using webviews. - - 2 On Edge, due to strict Same-origin policy, you must host the SDK files on the same domain as your web page. - - 3 Safari v11.x already has the required features, but it has many other issues, so we recommend v12+. - -Apart from the browsers, the operating systems may impose some limitations of their own that could restrict the use of the SDK. Browser compatibility ultimately depends on whether the browser on that particular operating system supports the features listed above. - -## How to Upgrade - -If you want to upgrade the SDK from an old version to a newer one, please see [how to upgrade](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/upgrade-guide/?ver=9.6.21&utm_source=guide). - -## Release Notes - -Learn about what are included in each release at [https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/release-notes/?ver=latest](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/release-notes/?ver=latest). - -## Next Steps - -Now that you have got the SDK integrated, you can choose to move forward in the following directions - -1. Check out the [Official Samples and Demo](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/index.html?ver=latest) -2. Learn how to make use of the [SDK features](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/user-guide/explore-features/index.html?ver=latest) -3. See how the SDK works in [Popular Use Cases](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/user-guide/use-cases/index.html?ver=latest) diff --git a/programming-old/javascript/user-guide/index-v9.6.30.md b/programming-old/javascript/user-guide/index-v9.6.30.md deleted file mode 100644 index fbc4603a..00000000 --- a/programming-old/javascript/user-guide/index-v9.6.30.md +++ /dev/null @@ -1,511 +0,0 @@ ---- -layout: default-layout -title: v9.6.30 User Guide - Dynamsoft Barcode Reader JavaScript Edition -description: This is the user guide of Dynamsoft Barcode Reader JavaScript SDK. -keywords: user guide, javascript, js -breadcrumbText: User Guide -noTitleIndex: true -needGenerateH3Content: true -needAutoGenerateSidebar: true -permalink: /programming/javascript/user-guide/index-v9.6.30.html -schema: schemas/dynamsoft-facilitates-mit-research-schema.json ---- - - - -# Barcode Reader for Your Website - User Guide - -[Dynamsoft Barcode Reader JavaScript Edition](https://www.dynamsoft.com/barcode-reader/sdk-javascript/) (DBR-JS) is equipped with industry-leading algorithms for exceptional speed, accuracy and read rates in barcode reading. Using its well-designed API, you can turn your web page into a barcode scanner with just a few lines of code. - -![version](https://img.shields.io/npm/v/dynamsoft-javascript-barcode.svg) -![downloads](https://img.shields.io/npm/dm/dynamsoft-javascript-barcode.svg) -![jsdelivr](https://img.shields.io/jsdelivr/npm/hm/dynamsoft-javascript-barcode.svg) -![vulnerabilities](https://img.shields.io/snyk/vulnerabilities/npm/dynamsoft-javascript-barcode.svg) - -Once the DBR-JS SDK gets integrated into your web page, your users can access a camera via the browser and read barcodes directly from its video input. - - - -In this guide, you will learn step by step on how to integrate the DBR-JS SDK into your website. - -Table of Contents - -- [Hello World - Simplest Implementation](#hello-world---simplest-implementation) - - [Understand the code](#understand-the-code) - - [Run the example](#run-the-example) -- [Building your own page](#building-your-own-page) - - [Include the SDK](#include-the-sdk) - - [Configure the SDK](#configure-the-sdk) - - [Interact with the SDK](#interact-with-the-sdk) - - [Customize the UI (optional)](#customize-the-ui-optional) -- [API Documentation](#api-documentation) -- [System Requirements](#system-requirements) -- [How to Upgrade](#how-to-upgrade) -- [Release Notes](#release-notes) -- [Next Steps](#next-steps) - -**Popular Examples** - -- Hello World - [Guide](#hello-world---simplest-implementation) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.30/1.hello-world/1.hello-world.html) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/1.hello-world.html?ver=9.6.30&utm_source=guide) -- Angular App - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/helloworld-angular.html?ver=9.6.30&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.30/1.hello-world/3.read-video-angular) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/3.read-video-angular/dist/hello-world/?ver=9.6.30&utm_source=guide) -- React App - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/helloworld-reactjs.html?ver=9.6.30&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.30/1.hello-world/4.read-video-react) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/4.read-video-react/build/?ver=9.6.30&utm_source=guide) -- Vue App - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/helloworld-vuejsv3.html?ver=9.6.30&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.30/1.hello-world/6.read-video-vue3) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/6.read-video-vue3/dist/?ver=9.6.30&utm_source=guide) -- PWA App - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/helloworld-pwa.html?ver=9.6.30&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.30/1.hello-world/10.read-video-pwa) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/10.read-video-pwa/helloworld-pwa.html?ver=9.6.30&utm_source=guide) -- WebView in Android and iOS - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/v9.6.30/1.hello-world/14.read-video-webview) -- Read Driver Licenses - [Guide](https://www.dynamsoft.com/barcode-reader/docs/core/programming/usecases/scan-and-parse-AAMVA.html?ver=9.6.30&utm_source=guide&&lang=js) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.30/4.use-case/2.read-a-drivers-license.html) \| [Run](https://demo.dynamsoft.com/samples/dbr/js/4.use-case/2.read-a-drivers-license.html?ver=9.6.30&utm_source=guide) -- Fill A Form - [Guide](https://www.dynamsoft.com/barcode-reader/docs/core/programming/usecases/scan-barcodes-as-input.html?lang=js&&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.30/4.use-case/1.fill-a-form-with-barcode-reading.html) \| [Run](https://demo.dynamsoft.com/samples/dbr/js/4.use-case/1.fill-a-form-with-barcode-reading.html?ver=9.6.30&utm_source=guide) -- Show result information on the video - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/main/4.use-case/3.show-result-texts-on-the-video.html) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/4.use-case/3.show-result-texts-on-the-video.html?ver=9.6.30&utm_source=guide) -- Debug Camera and Collect Video Frame - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/debug.html?lang=js&&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.30/5.others/debug) - -You can also: - -- Try the Official Demo - [Run](https://demo.dynamsoft.com/barcode-reader-js/?ver=9.6.30&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-demo/) -- Try Online Examples - [Run](https://demo.dynamsoft.com/Samples/DBR/JS/index.html?ver=9.6.30&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/v9.6.30/) - -## Hello World - Simplest Implementation - -Let's start with the "Hello World" example of the DBR-JS SDK which demonstrates how to use the minimum code to enable a web page to read barcodes from a live video stream. - -- Basic Requirements - - Internet connection - - [A supported browser](#system-requirements) - - Camera access - -### Understand the code - -The complete code of the "Hello World" example is shown below - -```html - - - - - - - - - -``` - -

- - Code in Github - -   - - Run via JSFiddle - -   - - Run in Dynamsoft - -

- ------ - -#### About the code - -- The DBR-JS SDK is included in the code via the **jsDelivr** CDN. - -> In some rare cases, you might not be able to access the CDN. If this happens, you can use [https://download2.dynamsoft.com/dbr/dynamsoft-barcode-reader-js/dynamsoft-barcode-reader-js-9.6.30/dist/dbr.js](https://download2.dynamsoft.com/dbr/dynamsoft-barcode-reader-js/dynamsoft-barcode-reader-js-9.6.30/dist/dbr.js) for the test. However, please DO NOT use CDN of `download2.dynamsoft.com` in your production application because it is temporary. Instead, you can try [hosting the SDK yourself](#host-the-sdk-yourself). - -- `license`: This property specifies a license key. Note that the license "DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9" used in this example is an online license and requires network connection to work. Read more on [Specify the license](#specify-the-license). - -- `createInstance()`: This method creates a `BarcodeScanner` object. This object can read barcodes directly from a video input with the help of its interactive UI (hidden by default) and the MediaDevices interface. - -- `onFrameRead`: This event is triggered every time the SDK finishes scanning a video frame. The `results` object contains all the barcode results that the SDK have found on this frame. In this example, we print the results to the browser console. - -- `onUniqueRead`: This event is triggered when the SDK finds a new barcode, which is not a duplicate among multiple frames. `txt` holds the barcode text value while `result` is an object that holds details of the barcode. In this example, an alert will be displayed for this new barcode. - -- `show()`: This method brings up the built-in UI of the `BarcodeScanner` object and starts scanning. - -### Run the example - -You can run the example deployed to the Dynamsoft Demo Server or test it with JSFiddle code editor. You will be asked to allow access to your camera, after which the video will be displayed on the page. After that, you can point the camera at a barcode to read it. - -When a barcode is decoded, you will see the result text pop up and the barcode location will be highlighted in the video feed. - -Alternatively, you can make a local test simply by taking the code in step 1, pasting it in a file with the name "hello-world.html" and open it in a browser. - -*Note*: - -If you open the web page as `file:///` or `http://` , the camera may not work correctly because the API getUserMedia usually requires HTTPS to access the camera. - -To make sure your web application can access the camera, please configure your web server to support HTTPS. The following links may help. - -1. NGINX: Configuring HTTPS servers -2. IIS: Create a Self Signed Certificate in IIS -3. Tomcat: Setting Up SSL on Tomcat in 5 minutes -4. Node.js: npm tls - -If the test doesn't go as expected, you can [contact us](https://www.dynamsoft.com/contact/?ver=9.6.30&utm_source=guide). - -## Building your own page - -### Include the SDK - -#### Use a public CDN - -The simplest way to include the SDK is to use either the [jsDelivr](https://jsdelivr.com/) or [UNPKG](https://unpkg.com/) CDN. The "hello world" example above uses **jsDelivr**. - -- jsDelivr - - ```html - - ``` - -- UNPKG - - ```html - - ``` - -#### Host the SDK yourself - -Besides using the public CDN, you can also download the SDK and host its files on your own server or a commercial CDN before including it in your application. - -Options to download the SDK: - -- From the website - - Download the JavaScript Package - -- yarn - - ```cmd - yarn add dynamsoft-javascript-barcode - ``` - -- npm - - ```cmd - npm install dynamsoft-javascript-barcode --save - ``` - -Depending on how you downloaded the SDK and how you intend to use it, you can typically include it like this: - -```html - -``` - -or - -```html - -``` - -or - -```typescript -import { BarcodeScanner } from 'dynamsoft-javascript-barcode'; -``` - -**NOTE** - -* Some older web application servers do not set `.wasm` mimetype as `application/wasm`. Upgrade your web application servers, or define the mimetype yourselves: - * [Apache](https://developer.mozilla.org/en-US/docs/Learn/Server-side/Apache_Configuration_htaccess#media_types_and_character_encodings) - * [IIS](https://docs.microsoft.com/en-us/iis/configuration/system.webserver/staticcontent/mimemap) - * [Nginx](https://www.nginx.com/resources/wiki/start/topics/examples/full/#mime-types) - -* To work properly, the SDK requires a few engine files, which are relatively large and may take quite a few seconds to download. We recommend that you set a longer cache time for these engine files, to maximize the performance of your web application. - - ```cmd - Cache-Control: max-age=31536000 - ``` - - Reference: [Cache-Control](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control). - -### Configure the SDK - -Before using the SDK, you need to configure a few things. - -#### Specify the license - -The SDK requires a license to work, use the API `license` to specify a license key. - -```javascript -Dynamsoft.DBR.BarcodeScanner.license = "YOUR-LICENSE-KEY"; -``` - -To test the SDK, you can request a 30-day trial license via the Request a Trial License link. - -> If you register a Dynamsoft account and download the SDK from the official website, Dynamsoft will automatically generate a 30-day trial license for you, and put the license key into all the samples attached to the SDK. - -#### Specify the location of the "engine" files - -This is usually only required with frameworks like Angular or React, etc. where dbr.js is compiled into another file. - -The purpose is to tell the SDK where to find the engine files (\*.worker.js, \*.wasm.js and \*.wasm, etc.). The API is called `engineResourcePath`: - -```javascript -//The following code uses the jsDelivr CDN, feel free to change it to your own location of these files -Dynamsoft.DBR.BarcodeScanner.engineResourcePath = "https://cdn.jsdelivr.net/npm/dynamsoft-javascript-barcode@9.6.30/dist/"; -``` - -### Interact with the SDK - -#### Create a `BarcodeScanner` object - -You can use one of two classes ( `BarcodeScanner` and `BarcodeReader` ) to interact with the SDK. `BarcodeReader` is a low-level class that processes images directly. `BarcodeScanner` , on the other hand, inherits from `BarcodeReader` and provides high-level APIs and a built-in GUI to allow continuous barcode scanning on video frames. We'll focus on `BarcodeScanner` in this guide. - -To use the SDK, we first create a `BarcodeScanner` object. - -```javascript -Dynamsoft.DBR.BarcodeScanner.license = "YOUR-LICENSE-KEY"; -let scanner = null; -try { - scanner = await Dynamsoft.DBR.BarcodeScanner.createInstance(); -} catch (ex) { - console.error(ex); -} -``` - -Tip: When creating a `BarcodeScanner` object within a function which may be called more than once, it's best to use a "helper" variable to avoid double creation such as `pScanner` in the following code - -```javascript -Dynamsoft.DBR.BarcodeScanner.license = "YOUR-LICENSE-KEY"; -let pScanner = null; -document.getElementById('btn-scan').addEventListener('click', async () => { - try { - const scanner = await (pScanner = pScanner || Dynamsoft.DBR.BarcodeScanner.createInstance()); - } catch (ex) { - console.error(ex); - } -}); -``` - -#### Customize the `BarcodeScanner` Settings (optional) - -Let's take a look at the following code snippets: - -```javascript -// Sets which camera and what resolution to use -let allCameras = await scanner.getAllCameras(); -await scanner.setCurrentCamera(allCameras[0].deviceId); -await scanner.setResolution(1280, 720); -``` - -```javascript -// Sets up the scanner behavior -let scanSettings = await scanner.getScanSettings(); -// Disregards duplicated results found in a specified time period (in milliseconds). -scanSettings.duplicateForgetTime = 5000; // The default is 3000 -// Sets a scan interval in milliseconds so the SDK may release the CPU from time to time. -// (setting this value larger is a simple way to save battery power and reduce device heating). -scanSettings.intervalTime = 100; // The default is 0. -// Sets captureAndDecodeInParallel to false, which tells the SDK not to acquire the next frame while decoding the first. -// This is another way to save battery power and is recommended on low-end phones. However, it does slow down the decoding speed. -scanSettings.captureAndDecodeInParallel = false; // The default is true. -await scanner.updateScanSettings(scanSettings); -``` - -```javascript -// Uses one of the built-in RuntimeSetting templates: "single" (decode a single barcode, the default mode), "speed", "balance", "coverage", "dense" and "distance" -await scanner.updateRuntimeSettings("speed"); - -// Makes changes to the template. The code below demonstrates how to specify enabled symbologies -let runtimeSettings = await scanner.getRuntimeSettings(); -runtimeSettings.barcodeFormatIds = Dynamsoft.DBR.EnumBarcodeFormat.BF_ONED | Dynamsoft.DBR.EnumBarcodeFormat.BF_QR_CODE; -await scanner.updateRuntimeSettings(runtimeSettings); -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/yfkcajxz/) - -As you can see from the above code snippets, there are three types of configurations: - -- Customize the data source: This configuration includes which camera to use, the preferred resolution, etc. Learn more here. - -- `get/updateScanSettings`: Configures the behavior of the scanner which includes `duplicateForgetTime` and `intervalTime`, etc. - -- `get/updateRuntimeSettings`: Configures the decode engine with either a built-in template or a comprehensive `RuntimeSettings` object. For example, the following uses the built-in "speed" settings with updated `localizationModes`. - - ```javascript - await barcodeScanner.updateRuntimeSettings("speed"); - //await barcodeScanner.updateRuntimeSettings("balance"); //alternative - //await barcodeScanner.updateRuntimeSettings("coverage"); //alternative - let settings = await barcodeScanner.getRuntimeSettings(); - settings.localizationModes = [ - Dynamsoft.DBR.EnumLocalizationMode.LM_CONNECTED_BLOCKS, - Dynamsoft.DBR.EnumLocalizationMode.LM_SCAN_DIRECTLY, - Dynamsoft.DBR.EnumLocalizationMode.LM_LINES, 0, 0, 0, 0, 0 - ]; - await barcodeScanner.updateRuntimeSettings(settings); - ``` - - Try in [JSFiddle](https://jsfiddle.net/DynamsoftTeam/f24h8c1m/). - - See also [settings samples](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/parameter-settings.html?ver=9.6.30&utm_source=guide). - -> Find the full list of the runtime settings here. - -### Customize the UI (optional) - -The built-in UI of the `BarcodeScanner` object is defined in the file `dist/dbr.ui.html` . There are a few ways to customize it: - -#### Modify the file `dist/dbr.ui.html` directly - - This option is only possible when you [Host the SDK yourself](#host-the-sdk-yourself) instead of using a public CDN. - -#### Copy the file `dist/dbr.ui.html` to your application, modify it and use the the API `defaultUIElementURL` to set it as the default UI - - ```javascript - // This line only takes effect before the method `createInstance()` is called. - Dynamsoft.DBR.BarcodeScanner.defaultUIElementURL = "THE-URL-TO-THE-FILE"; - ``` - -#### Append the default UI element to your page, customize it before showing it - - ```html -
- ``` - - ```javascript - document.getElementById('div-ui-container').appendChild(scanner.getUIElement()); - document.getElementsByClassName('dce-btn-close')[0].hidden = true; // Hide the close button - ``` - -#### Build the UI element from scratch and connect it to the SDK with the API `setUIElement(HTMLElement)` - -1. **Embed the video** - - ```html -
-
-
- - ``` - - > 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` . - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/2jzeq1r6/) - -2. **[Optional] Add the camera list and resolution list** - - If the class names of the created select elements match the default class names, i.e. `dce-sel-camera` and `dce-sel-resolution` respectively, the SDK will automatically populate the lists and handle the camera/resolution switching. - - ```html -
-
-
-
- ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/nbj75vxu/) - - ```html -
- - -
-
-
- ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/25v08paf/) - - > By default, only 3 hard-coded resolutions (1920 x 1080, 1280 x 720,640 x 480) are populated as options. You can show a customized set of options by hardcoding them. - - ```html - - ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/tnfjks4q/) - - > Generally, you need to provide a resolution that the camera supports. However, in case a camera does not support the specified resolution, it usually uses the closest supported resolution. As a result, the selected resolution may not be the actual resolution. In this case, add an option with the class name `dce-opt-gotResolution` (as shown above) and the SDK will automatically use it to show the **actual resolution**. - - See the section of the Explore Features guide on [UI customization]({{site.features}}customize-the-ui.html?lang=js) to learn more. - -## API Documentation - -You can check out the detailed documentation about the APIs of the SDK at -[https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/?ver=9.6.30](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/?ver=9.6.30). - -## System Requirements - -DBR requires the following features to work: - -- Secure context (HTTPS deployment) - - When deploying your application / website for production, make sure to serve it via a secure HTTPS connection. This is required for two reasons - - - Access to the camera video stream is only granted in a security context. Most browsers impose this restriction. - > Some browsers like Chrome may grant the access for `http://127.0.0.1` and `http://localhost` or even for pages opened directly from the local disk (`file:///...`). This can be helpful for temporary development and test. - - - Dynamsoft License requires a secure context to work. - -- `WebAssembly`, `Blob`, `URL`/`createObjectURL`, `Web Workers` - - The above four features are required for the SDK to work. - -- `MediaDevices`/`getUserMedia` - - This API is only required for in-browser video streaming. If a browser does not support this API, the [Single Frame Mode](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/BarcodeScanner.html?ver=9.6.30&utm_source=guide#singleframemode) will be used automatically. If the API exists but doesn't work correctly, the Single Frame Mode can be used as an alternative way to access the camera. - -- `getSettings` - - This API inspects the video input which is a `MediaStreamTrack` object about its constrainable properties. - -The following table is a list of supported browsers based on the above requirements: - - Browser Name | Version - :-: | :-: - Chrome | v59+1 - Firefox | v52+ (v55+ on Android/iOS1) - Edge2 | v16+ - Safari3 | v11+ - - 1 iOS 14.3+ is required for camera video streaming in Chrome and Firefox or Apps using webviews. - - 2 On Edge, due to strict Same-origin policy, you must host the SDK files on the same domain as your web page. - - 3 Safari v11.x already has the required features, but it has many other issues, so we recommend v12+. - -Apart from the browsers, the operating systems may impose some limitations of their own that could restrict the use of the SDK. Browser compatibility ultimately depends on whether the browser on that particular operating system supports the features listed above. - -## How to Upgrade - -If you want to upgrade the SDK from an old version to a newer one, please see [how to upgrade](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/upgrade-guide/?ver=9.6.30&utm_source=guide). - -## Release Notes - -Learn about what are included in each release at [https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/release-notes/?ver=latest](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/release-notes/?ver=latest). - -## Next Steps - -Now that you have got the SDK integrated, you can choose to move forward in the following directions - -1. Check out the [Official Samples and Demo](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/index.html?ver=latest) -2. Learn how to make use of the [SDK features](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/user-guide/explore-features/index.html?ver=latest) -3. See how the SDK works in [Popular Use Cases](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/user-guide/use-cases/index.html?ver=latest) diff --git a/programming-old/javascript/user-guide/index-v9.6.31.md b/programming-old/javascript/user-guide/index-v9.6.31.md deleted file mode 100644 index 4a1aae17..00000000 --- a/programming-old/javascript/user-guide/index-v9.6.31.md +++ /dev/null @@ -1,511 +0,0 @@ ---- -layout: default-layout -title: v9.6.31 User Guide - Dynamsoft Barcode Reader JavaScript Edition -description: This is the user guide of Dynamsoft Barcode Reader JavaScript SDK. -keywords: user guide, javascript, js -breadcrumbText: User Guide -noTitleIndex: true -needGenerateH3Content: true -needAutoGenerateSidebar: true -permalink: /programming/javascript/user-guide/index-v9.6.31.html -schema: schemas/dynamsoft-facilitates-mit-research-schema.json ---- - - - -# Barcode Reader for Your Website - User Guide - -[Dynamsoft Barcode Reader JavaScript Edition](https://www.dynamsoft.com/barcode-reader/sdk-javascript/) (DBR-JS) is equipped with industry-leading algorithms for exceptional speed, accuracy and read rates in barcode reading. Using its well-designed API, you can turn your web page into a barcode scanner with just a few lines of code. - -![version](https://img.shields.io/npm/v/dynamsoft-javascript-barcode.svg) -![downloads](https://img.shields.io/npm/dm/dynamsoft-javascript-barcode.svg) -![jsdelivr](https://img.shields.io/jsdelivr/npm/hm/dynamsoft-javascript-barcode.svg) -![vulnerabilities](https://img.shields.io/snyk/vulnerabilities/npm/dynamsoft-javascript-barcode.svg) - -Once the DBR-JS SDK gets integrated into your web page, your users can access a camera via the browser and read barcodes directly from its video input. - - - -In this guide, you will learn step by step on how to integrate the DBR-JS SDK into your website. - -Table of Contents - -- [Hello World - Simplest Implementation](#hello-world---simplest-implementation) - - [Understand the code](#understand-the-code) - - [Run the example](#run-the-example) -- [Building your own page](#building-your-own-page) - - [Include the SDK](#include-the-sdk) - - [Configure the SDK](#configure-the-sdk) - - [Interact with the SDK](#interact-with-the-sdk) - - [Customize the UI (optional)](#customize-the-ui-optional) -- [API Documentation](#api-documentation) -- [System Requirements](#system-requirements) -- [How to Upgrade](#how-to-upgrade) -- [Release Notes](#release-notes) -- [Next Steps](#next-steps) - -**Popular Examples** - -- Hello World - [Guide](#hello-world---simplest-implementation) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.31/1.hello-world/1.hello-world.html) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/1.hello-world.html?ver=9.6.31&utm_source=guide) -- Angular App - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/helloworld-angular.html?ver=9.6.31&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.31/1.hello-world/3.read-video-angular) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/3.read-video-angular/dist/hello-world/?ver=9.6.31&utm_source=guide) -- React App - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/helloworld-reactjs.html?ver=9.6.31&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.31/1.hello-world/4.read-video-react) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/4.read-video-react/build/?ver=9.6.31&utm_source=guide) -- Vue App - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/helloworld-vuejsv3.html?ver=9.6.31&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.31/1.hello-world/6.read-video-vue3) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/6.read-video-vue3/dist/?ver=9.6.31&utm_source=guide) -- PWA App - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/helloworld-pwa.html?ver=9.6.31&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.31/1.hello-world/10.read-video-pwa) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/10.read-video-pwa/helloworld-pwa.html?ver=9.6.31&utm_source=guide) -- WebView in Android and iOS - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/v9.6.31/1.hello-world/14.read-video-webview) -- Read Driver Licenses - [Guide](https://www.dynamsoft.com/barcode-reader/docs/core/programming/usecases/scan-and-parse-AAMVA.html?ver=9.6.31&utm_source=guide&&lang=js) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.31/4.use-case/2.read-a-drivers-license.html) \| [Run](https://demo.dynamsoft.com/samples/dbr/js/4.use-case/2.read-a-drivers-license.html?ver=9.6.31&utm_source=guide) -- Fill A Form - [Guide](https://www.dynamsoft.com/barcode-reader/docs/core/programming/usecases/scan-barcodes-as-input.html?lang=js&&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.31/4.use-case/1.fill-a-form-with-barcode-reading.html) \| [Run](https://demo.dynamsoft.com/samples/dbr/js/4.use-case/1.fill-a-form-with-barcode-reading.html?ver=9.6.31&utm_source=guide) -- Show result information on the video - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/main/4.use-case/3.show-result-texts-on-the-video.html) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/4.use-case/3.show-result-texts-on-the-video.html?ver=9.6.31&utm_source=guide) -- Debug Camera and Collect Video Frame - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/debug.html?lang=js&&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.31/5.others/debug) - -You can also: - -- Try the Official Demo - [Run](https://demo.dynamsoft.com/barcode-reader-js/?ver=9.6.31&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-demo/) -- Try Online Examples - [Run](https://demo.dynamsoft.com/Samples/DBR/JS/index.html?ver=9.6.31&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/v9.6.31/) - -## Hello World - Simplest Implementation - -Let's start with the "Hello World" example of the DBR-JS SDK which demonstrates how to use the minimum code to enable a web page to read barcodes from a live video stream. - -- Basic Requirements - - Internet connection - - [A supported browser](#system-requirements) - - Camera access - -### Understand the code - -The complete code of the "Hello World" example is shown below - -```html - - - - - - - - - -``` - -

- - Code in Github - -   - - Run via JSFiddle - -   - - Run in Dynamsoft - -

- ------ - -#### About the code - -- The DBR-JS SDK is included in the code via the **jsDelivr** CDN. - -> In some rare cases, you might not be able to access the CDN. If this happens, you can use [https://download2.dynamsoft.com/dbr/dynamsoft-barcode-reader-js/dynamsoft-barcode-reader-js-9.6.31/dist/dbr.js](https://download2.dynamsoft.com/dbr/dynamsoft-barcode-reader-js/dynamsoft-barcode-reader-js-9.6.31/dist/dbr.js) for the test. However, please DO NOT use CDN of `download2.dynamsoft.com` in your production application because it is temporary. Instead, you can try [hosting the SDK yourself](#host-the-sdk-yourself). - -- `license`: This property specifies a license key. Note that the license "DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9" used in this example is an online license and requires network connection to work. Read more on [Specify the license](#specify-the-license). - -- `createInstance()`: This method creates a `BarcodeScanner` object. This object can read barcodes directly from a video input with the help of its interactive UI (hidden by default) and the MediaDevices interface. - -- `onFrameRead`: This event is triggered every time the SDK finishes scanning a video frame. The `results` object contains all the barcode results that the SDK have found on this frame. In this example, we print the results to the browser console. - -- `onUniqueRead`: This event is triggered when the SDK finds a new barcode, which is not a duplicate among multiple frames. `txt` holds the barcode text value while `result` is an object that holds details of the barcode. In this example, an alert will be displayed for this new barcode. - -- `show()`: This method brings up the built-in UI of the `BarcodeScanner` object and starts scanning. - -### Run the example - -You can run the example deployed to the Dynamsoft Demo Server or test it with JSFiddle code editor. You will be asked to allow access to your camera, after which the video will be displayed on the page. After that, you can point the camera at a barcode to read it. - -When a barcode is decoded, you will see the result text pop up and the barcode location will be highlighted in the video feed. - -Alternatively, you can make a local test simply by taking the code in step 1, pasting it in a file with the name "hello-world.html" and open it in a browser. - -*Note*: - -If you open the web page as `file:///` or `http://` , the camera may not work correctly because the API getUserMedia usually requires HTTPS to access the camera. - -To make sure your web application can access the camera, please configure your web server to support HTTPS. The following links may help. - -1. NGINX: Configuring HTTPS servers -2. IIS: Create a Self Signed Certificate in IIS -3. Tomcat: Setting Up SSL on Tomcat in 5 minutes -4. Node.js: npm tls - -If the test doesn't go as expected, you can [contact us](https://www.dynamsoft.com/contact/?ver=9.6.31&utm_source=guide). - -## Building your own page - -### Include the SDK - -#### Use a public CDN - -The simplest way to include the SDK is to use either the [jsDelivr](https://jsdelivr.com/) or [UNPKG](https://unpkg.com/) CDN. The "hello world" example above uses **jsDelivr**. - -- jsDelivr - - ```html - - ``` - -- UNPKG - - ```html - - ``` - -#### Host the SDK yourself - -Besides using the public CDN, you can also download the SDK and host its files on your own server or a commercial CDN before including it in your application. - -Options to download the SDK: - -- From the website - - Download the JavaScript Package - -- yarn - - ```cmd - yarn add dynamsoft-javascript-barcode - ``` - -- npm - - ```cmd - npm install dynamsoft-javascript-barcode --save - ``` - -Depending on how you downloaded the SDK and how you intend to use it, you can typically include it like this: - -```html - -``` - -or - -```html - -``` - -or - -```typescript -import { BarcodeScanner } from 'dynamsoft-javascript-barcode'; -``` - -**NOTE** - -* Some older web application servers do not set `.wasm` mimetype as `application/wasm`. Upgrade your web application servers, or define the mimetype yourselves: - * [Apache](https://developer.mozilla.org/en-US/docs/Learn/Server-side/Apache_Configuration_htaccess#media_types_and_character_encodings) - * [IIS](https://docs.microsoft.com/en-us/iis/configuration/system.webserver/staticcontent/mimemap) - * [Nginx](https://www.nginx.com/resources/wiki/start/topics/examples/full/#mime-types) - -* To work properly, the SDK requires a few engine files, which are relatively large and may take quite a few seconds to download. We recommend that you set a longer cache time for these engine files, to maximize the performance of your web application. - - ```cmd - Cache-Control: max-age=31536000 - ``` - - Reference: [Cache-Control](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control). - -### Configure the SDK - -Before using the SDK, you need to configure a few things. - -#### Specify the license - -The SDK requires a license to work, use the API `license` to specify a license key. - -```javascript -Dynamsoft.DBR.BarcodeScanner.license = "YOUR-LICENSE-KEY"; -``` - -To test the SDK, you can request a 30-day trial license via the Request a Trial License link. - -> If you register a Dynamsoft account and download the SDK from the official website, Dynamsoft will automatically generate a 30-day trial license for you, and put the license key into all the samples attached to the SDK. - -#### Specify the location of the "engine" files - -This is usually only required with frameworks like Angular or React, etc. where dbr.js is compiled into another file. - -The purpose is to tell the SDK where to find the engine files (\*.worker.js, \*.wasm.js and \*.wasm, etc.). The API is called `engineResourcePath`: - -```javascript -//The following code uses the jsDelivr CDN, feel free to change it to your own location of these files -Dynamsoft.DBR.BarcodeScanner.engineResourcePath = "https://cdn.jsdelivr.net/npm/dynamsoft-javascript-barcode@9.6.31/dist/"; -``` - -### Interact with the SDK - -#### Create a `BarcodeScanner` object - -You can use one of two classes ( `BarcodeScanner` and `BarcodeReader` ) to interact with the SDK. `BarcodeReader` is a low-level class that processes images directly. `BarcodeScanner` , on the other hand, inherits from `BarcodeReader` and provides high-level APIs and a built-in GUI to allow continuous barcode scanning on video frames. We'll focus on `BarcodeScanner` in this guide. - -To use the SDK, we first create a `BarcodeScanner` object. - -```javascript -Dynamsoft.DBR.BarcodeScanner.license = "YOUR-LICENSE-KEY"; -let scanner = null; -try { - scanner = await Dynamsoft.DBR.BarcodeScanner.createInstance(); -} catch (ex) { - console.error(ex); -} -``` - -Tip: When creating a `BarcodeScanner` object within a function which may be called more than once, it's best to use a "helper" variable to avoid double creation such as `pScanner` in the following code - -```javascript -Dynamsoft.DBR.BarcodeScanner.license = "YOUR-LICENSE-KEY"; -let pScanner = null; -document.getElementById('btn-scan').addEventListener('click', async () => { - try { - const scanner = await (pScanner = pScanner || Dynamsoft.DBR.BarcodeScanner.createInstance()); - } catch (ex) { - console.error(ex); - } -}); -``` - -#### Customize the `BarcodeScanner` Settings (optional) - -Let's take a look at the following code snippets: - -```javascript -// Sets which camera and what resolution to use -let allCameras = await scanner.getAllCameras(); -await scanner.setCurrentCamera(allCameras[0].deviceId); -await scanner.setResolution(1280, 720); -``` - -```javascript -// Sets up the scanner behavior -let scanSettings = await scanner.getScanSettings(); -// Disregards duplicated results found in a specified time period (in milliseconds). -scanSettings.duplicateForgetTime = 5000; // The default is 3000 -// Sets a scan interval in milliseconds so the SDK may release the CPU from time to time. -// (setting this value larger is a simple way to save battery power and reduce device heating). -scanSettings.intervalTime = 100; // The default is 0. -// Sets captureAndDecodeInParallel to false, which tells the SDK not to acquire the next frame while decoding the first. -// This is another way to save battery power and is recommended on low-end phones. However, it does slow down the decoding speed. -scanSettings.captureAndDecodeInParallel = false; // The default is true. -await scanner.updateScanSettings(scanSettings); -``` - -```javascript -// Uses one of the built-in RuntimeSetting templates: "single" (decode a single barcode, the default mode), "speed", "balance", "coverage", "dense" and "distance" -await scanner.updateRuntimeSettings("speed"); - -// Makes changes to the template. The code below demonstrates how to specify enabled symbologies -let runtimeSettings = await scanner.getRuntimeSettings(); -runtimeSettings.barcodeFormatIds = Dynamsoft.DBR.EnumBarcodeFormat.BF_ONED | Dynamsoft.DBR.EnumBarcodeFormat.BF_QR_CODE; -await scanner.updateRuntimeSettings(runtimeSettings); -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/yfkcajxz/) - -As you can see from the above code snippets, there are three types of configurations: - -- Customize the data source: This configuration includes which camera to use, the preferred resolution, etc. Learn more here. - -- `get/updateScanSettings`: Configures the behavior of the scanner which includes `duplicateForgetTime` and `intervalTime`, etc. - -- `get/updateRuntimeSettings`: Configures the decode engine with either a built-in template or a comprehensive `RuntimeSettings` object. For example, the following uses the built-in "speed" settings with updated `localizationModes`. - - ```javascript - await barcodeScanner.updateRuntimeSettings("speed"); - //await barcodeScanner.updateRuntimeSettings("balance"); //alternative - //await barcodeScanner.updateRuntimeSettings("coverage"); //alternative - let settings = await barcodeScanner.getRuntimeSettings(); - settings.localizationModes = [ - Dynamsoft.DBR.EnumLocalizationMode.LM_CONNECTED_BLOCKS, - Dynamsoft.DBR.EnumLocalizationMode.LM_SCAN_DIRECTLY, - Dynamsoft.DBR.EnumLocalizationMode.LM_LINES, 0, 0, 0, 0, 0 - ]; - await barcodeScanner.updateRuntimeSettings(settings); - ``` - - Try in [JSFiddle](https://jsfiddle.net/DynamsoftTeam/f24h8c1m/). - - See also [settings samples](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/parameter-settings.html?ver=9.6.31&utm_source=guide). - -> Find the full list of the runtime settings here. - -### Customize the UI (optional) - -The built-in UI of the `BarcodeScanner` object is defined in the file `dist/dbr.ui.html` . There are a few ways to customize it: - -#### Modify the file `dist/dbr.ui.html` directly - - This option is only possible when you [Host the SDK yourself](#host-the-sdk-yourself) instead of using a public CDN. - -#### Copy the file `dist/dbr.ui.html` to your application, modify it and use the the API `defaultUIElementURL` to set it as the default UI - - ```javascript - // This line only takes effect before the method `createInstance()` is called. - Dynamsoft.DBR.BarcodeScanner.defaultUIElementURL = "THE-URL-TO-THE-FILE"; - ``` - -#### Append the default UI element to your page, customize it before showing it - - ```html -
- ``` - - ```javascript - document.getElementById('div-ui-container').appendChild(scanner.getUIElement()); - document.getElementsByClassName('dce-btn-close')[0].hidden = true; // Hide the close button - ``` - -#### Build the UI element from scratch and connect it to the SDK with the API `setUIElement(HTMLElement)` - -1. **Embed the video** - - ```html -
-
-
- - ``` - - > 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` . - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/2jzeq1r6/) - -2. **[Optional] Add the camera list and resolution list** - - If the class names of the created select elements match the default class names, i.e. `dce-sel-camera` and `dce-sel-resolution` respectively, the SDK will automatically populate the lists and handle the camera/resolution switching. - - ```html -
-
-
-
- ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/nbj75vxu/) - - ```html -
- - -
-
-
- ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/25v08paf/) - - > By default, only 3 hard-coded resolutions (1920 x 1080, 1280 x 720,640 x 480) are populated as options. You can show a customized set of options by hardcoding them. - - ```html - - ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/tnfjks4q/) - - > Generally, you need to provide a resolution that the camera supports. However, in case a camera does not support the specified resolution, it usually uses the closest supported resolution. As a result, the selected resolution may not be the actual resolution. In this case, add an option with the class name `dce-opt-gotResolution` (as shown above) and the SDK will automatically use it to show the **actual resolution**. - - See the section of the Explore Features guide on [UI customization]({{site.features}}customize-the-ui.html?lang=js) to learn more. - -## API Documentation - -You can check out the detailed documentation about the APIs of the SDK at -[https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/?ver=9.6.31](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/?ver=9.6.31). - -## System Requirements - -DBR requires the following features to work: - -- Secure context (HTTPS deployment) - - When deploying your application / website for production, make sure to serve it via a secure HTTPS connection. This is required for two reasons - - - Access to the camera video stream is only granted in a security context. Most browsers impose this restriction. - > Some browsers like Chrome may grant the access for `http://127.0.0.1` and `http://localhost` or even for pages opened directly from the local disk (`file:///...`). This can be helpful for temporary development and test. - - - Dynamsoft License requires a secure context to work. - -- `WebAssembly`, `Blob`, `URL`/`createObjectURL`, `Web Workers` - - The above four features are required for the SDK to work. - -- `MediaDevices`/`getUserMedia` - - This API is only required for in-browser video streaming. If a browser does not support this API, the [Single Frame Mode](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/BarcodeScanner.html?ver=9.6.31&utm_source=guide#singleframemode) will be used automatically. If the API exists but doesn't work correctly, the Single Frame Mode can be used as an alternative way to access the camera. - -- `getSettings` - - This API inspects the video input which is a `MediaStreamTrack` object about its constrainable properties. - -The following table is a list of supported browsers based on the above requirements: - - Browser Name | Version - :-: | :-: - Chrome | v59+1 - Firefox | v52+ (v55+ on Android/iOS1) - Edge2 | v16+ - Safari3 | v11+ - - 1 iOS 14.3+ is required for camera video streaming in Chrome and Firefox or Apps using webviews. - - 2 On Edge, due to strict Same-origin policy, you must host the SDK files on the same domain as your web page. - - 3 Safari v11.x already has the required features, but it has many other issues, so we recommend v12+. - -Apart from the browsers, the operating systems may impose some limitations of their own that could restrict the use of the SDK. Browser compatibility ultimately depends on whether the browser on that particular operating system supports the features listed above. - -## How to Upgrade - -If you want to upgrade the SDK from an old version to a newer one, please see [how to upgrade](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/upgrade-guide/?ver=9.6.31&utm_source=guide). - -## Release Notes - -Learn about what are included in each release at [https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/release-notes/?ver=latest](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/release-notes/?ver=latest). - -## Next Steps - -Now that you have got the SDK integrated, you can choose to move forward in the following directions - -1. Check out the [Official Samples and Demo](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/index.html?ver=latest) -2. Learn how to make use of the [SDK features](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/user-guide/explore-features/index.html?ver=latest) -3. See how the SDK works in [Popular Use Cases](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/user-guide/use-cases/index.html?ver=latest) diff --git a/programming-old/javascript/user-guide/index-v9.6.32.md b/programming-old/javascript/user-guide/index-v9.6.32.md deleted file mode 100644 index 3a8f94c2..00000000 --- a/programming-old/javascript/user-guide/index-v9.6.32.md +++ /dev/null @@ -1,511 +0,0 @@ ---- -layout: default-layout -title: v9.6.32 User Guide - Dynamsoft Barcode Reader JavaScript Edition -description: This is the user guide of Dynamsoft Barcode Reader JavaScript SDK. -keywords: user guide, javascript, js -breadcrumbText: User Guide -noTitleIndex: true -needGenerateH3Content: true -needAutoGenerateSidebar: true -permalink: /programming/javascript/user-guide/index-v9.6.32.html -schema: schemas/dynamsoft-facilitates-mit-research-schema.json ---- - - - -# Barcode Reader for Your Website - User Guide - -[Dynamsoft Barcode Reader JavaScript Edition](https://www.dynamsoft.com/barcode-reader/sdk-javascript/) (DBR-JS) is equipped with industry-leading algorithms for exceptional speed, accuracy and read rates in barcode reading. Using its well-designed API, you can turn your web page into a barcode scanner with just a few lines of code. - -![version](https://img.shields.io/npm/v/dynamsoft-javascript-barcode.svg) -![downloads](https://img.shields.io/npm/dm/dynamsoft-javascript-barcode.svg) -![jsdelivr](https://img.shields.io/jsdelivr/npm/hm/dynamsoft-javascript-barcode.svg) -![vulnerabilities](https://img.shields.io/snyk/vulnerabilities/npm/dynamsoft-javascript-barcode.svg) - -Once the DBR-JS SDK gets integrated into your web page, your users can access a camera via the browser and read barcodes directly from its video input. - - - -In this guide, you will learn step by step on how to integrate the DBR-JS SDK into your website. - -Table of Contents - -- [Hello World - Simplest Implementation](#hello-world---simplest-implementation) - - [Understand the code](#understand-the-code) - - [Run the example](#run-the-example) -- [Building your own page](#building-your-own-page) - - [Include the SDK](#include-the-sdk) - - [Configure the SDK](#configure-the-sdk) - - [Interact with the SDK](#interact-with-the-sdk) - - [Customize the UI (optional)](#customize-the-ui-optional) -- [API Documentation](#api-documentation) -- [System Requirements](#system-requirements) -- [How to Upgrade](#how-to-upgrade) -- [Release Notes](#release-notes) -- [Next Steps](#next-steps) - -**Popular Examples** - -- Hello World - [Guide](#hello-world---simplest-implementation) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.32/1.hello-world/1.hello-world.html) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/1.hello-world.html?ver=9.6.32&utm_source=guide) -- Angular App - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/helloworld-angular.html?ver=9.6.32&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.32/1.hello-world/3.read-video-angular) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/3.read-video-angular/dist/hello-world/?ver=9.6.32&utm_source=guide) -- React App - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/helloworld-reactjs.html?ver=9.6.32&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.32/1.hello-world/4.read-video-react) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/4.read-video-react/build/?ver=9.6.32&utm_source=guide) -- Vue App - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/helloworld-vuejsv3.html?ver=9.6.32&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.32/1.hello-world/6.read-video-vue3) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/6.read-video-vue3/dist/?ver=9.6.32&utm_source=guide) -- PWA App - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/helloworld-pwa.html?ver=9.6.32&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.32/1.hello-world/10.read-video-pwa) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/10.read-video-pwa/helloworld-pwa.html?ver=9.6.32&utm_source=guide) -- WebView in Android and iOS - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/v9.6.32/1.hello-world/14.read-video-webview) -- Read Driver Licenses - [Guide](https://www.dynamsoft.com/barcode-reader/docs/core/programming/usecases/scan-and-parse-AAMVA.html?ver=9.6.32&utm_source=guide&&lang=js) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.32/4.use-case/2.read-a-drivers-license.html) \| [Run](https://demo.dynamsoft.com/samples/dbr/js/4.use-case/2.read-a-drivers-license.html?ver=9.6.32&utm_source=guide) -- Fill A Form - [Guide](https://www.dynamsoft.com/barcode-reader/docs/core/programming/usecases/scan-barcodes-as-input.html?lang=js&&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.32/4.use-case/1.fill-a-form-with-barcode-reading.html) \| [Run](https://demo.dynamsoft.com/samples/dbr/js/4.use-case/1.fill-a-form-with-barcode-reading.html?ver=9.6.32&utm_source=guide) -- Show result information on the video - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/main/4.use-case/3.show-result-texts-on-the-video.html) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/4.use-case/3.show-result-texts-on-the-video.html?ver=9.6.32&utm_source=guide) -- Debug Camera and Collect Video Frame - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/debug.html?lang=js&&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.32/5.others/debug) - -You can also: - -- Try the Official Demo - [Run](https://demo.dynamsoft.com/barcode-reader-js/?ver=9.6.32&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-demo/) -- Try Online Examples - [Run](https://demo.dynamsoft.com/Samples/DBR/JS/index.html?ver=9.6.32&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/v9.6.32/) - -## Hello World - Simplest Implementation - -Let's start with the "Hello World" example of the DBR-JS SDK which demonstrates how to use the minimum code to enable a web page to read barcodes from a live video stream. - -- Basic Requirements - - Internet connection - - [A supported browser](#system-requirements) - - Camera access - -### Understand the code - -The complete code of the "Hello World" example is shown below - -```html - - - - - - - - - -``` - -

- - Code in Github - -   - - Run via JSFiddle - -   - - Run in Dynamsoft - -

- ------ - -#### About the code - -- The DBR-JS SDK is included in the code via the **jsDelivr** CDN. - -> In some rare cases, you might not be able to access the CDN. If this happens, you can use [https://download2.dynamsoft.com/dbr/dynamsoft-barcode-reader-js/dynamsoft-barcode-reader-js-9.6.32/dist/dbr.js](https://download2.dynamsoft.com/dbr/dynamsoft-barcode-reader-js/dynamsoft-barcode-reader-js-9.6.32/dist/dbr.js) for the test. However, please DO NOT use CDN of `download2.dynamsoft.com` in your production application because it is temporary. Instead, you can try [hosting the SDK yourself](#host-the-sdk-yourself). - -- `license`: This property specifies a license key. Note that the license "DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9" used in this example is an online license and requires network connection to work. Read more on [Specify the license](#specify-the-license). - -- `createInstance()`: This method creates a `BarcodeScanner` object. This object can read barcodes directly from a video input with the help of its interactive UI (hidden by default) and the MediaDevices interface. - -- `onFrameRead`: This event is triggered every time the SDK finishes scanning a video frame. The `results` object contains all the barcode results that the SDK have found on this frame. In this example, we print the results to the browser console. - -- `onUniqueRead`: This event is triggered when the SDK finds a new barcode, which is not a duplicate among multiple frames. `txt` holds the barcode text value while `result` is an object that holds details of the barcode. In this example, an alert will be displayed for this new barcode. - -- `show()`: This method brings up the built-in UI of the `BarcodeScanner` object and starts scanning. - -### Run the example - -You can run the example deployed to the Dynamsoft Demo Server or test it with JSFiddle code editor. You will be asked to allow access to your camera, after which the video will be displayed on the page. After that, you can point the camera at a barcode to read it. - -When a barcode is decoded, you will see the result text pop up and the barcode location will be highlighted in the video feed. - -Alternatively, you can make a local test simply by taking the code in step 1, pasting it in a file with the name "hello-world.html" and open it in a browser. - -*Note*: - -If you open the web page as `file:///` or `http://` , the camera may not work correctly because the API getUserMedia usually requires HTTPS to access the camera. - -To make sure your web application can access the camera, please configure your web server to support HTTPS. The following links may help. - -1. NGINX: Configuring HTTPS servers -2. IIS: Create a Self Signed Certificate in IIS -3. Tomcat: Setting Up SSL on Tomcat in 5 minutes -4. Node.js: npm tls - -If the test doesn't go as expected, you can [contact us](https://www.dynamsoft.com/contact/?ver=9.6.32&utm_source=guide). - -## Building your own page - -### Include the SDK - -#### Use a public CDN - -The simplest way to include the SDK is to use either the [jsDelivr](https://jsdelivr.com/) or [UNPKG](https://unpkg.com/) CDN. The "hello world" example above uses **jsDelivr**. - -- jsDelivr - - ```html - - ``` - -- UNPKG - - ```html - - ``` - -#### Host the SDK yourself - -Besides using the public CDN, you can also download the SDK and host its files on your own server or a commercial CDN before including it in your application. - -Options to download the SDK: - -- From the website - - Download the JavaScript Package - -- yarn - - ```cmd - yarn add dynamsoft-javascript-barcode - ``` - -- npm - - ```cmd - npm install dynamsoft-javascript-barcode --save - ``` - -Depending on how you downloaded the SDK and how you intend to use it, you can typically include it like this: - -```html - -``` - -or - -```html - -``` - -or - -```typescript -import { BarcodeScanner } from 'dynamsoft-javascript-barcode'; -``` - -**NOTE** - -* Some older web application servers do not set `.wasm` mimetype as `application/wasm`. Upgrade your web application servers, or define the mimetype yourselves: - * [Apache](https://developer.mozilla.org/en-US/docs/Learn/Server-side/Apache_Configuration_htaccess#media_types_and_character_encodings) - * [IIS](https://docs.microsoft.com/en-us/iis/configuration/system.webserver/staticcontent/mimemap) - * [Nginx](https://www.nginx.com/resources/wiki/start/topics/examples/full/#mime-types) - -* To work properly, the SDK requires a few engine files, which are relatively large and may take quite a few seconds to download. We recommend that you set a longer cache time for these engine files, to maximize the performance of your web application. - - ```cmd - Cache-Control: max-age=31536000 - ``` - - Reference: [Cache-Control](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control). - -### Configure the SDK - -Before using the SDK, you need to configure a few things. - -#### Specify the license - -The SDK requires a license to work, use the API `license` to specify a license key. - -```javascript -Dynamsoft.DBR.BarcodeScanner.license = "YOUR-LICENSE-KEY"; -``` - -To test the SDK, you can request a 30-day trial license via the Request a Trial License link. - -> If you register a Dynamsoft account and download the SDK from the official website, Dynamsoft will automatically generate a 30-day trial license for you, and put the license key into all the samples attached to the SDK. - -#### Specify the location of the "engine" files - -This is usually only required with frameworks like Angular or React, etc. where dbr.js is compiled into another file. - -The purpose is to tell the SDK where to find the engine files (\*.worker.js, \*.wasm.js and \*.wasm, etc.). The API is called `engineResourcePath`: - -```javascript -//The following code uses the jsDelivr CDN, feel free to change it to your own location of these files -Dynamsoft.DBR.BarcodeScanner.engineResourcePath = "https://cdn.jsdelivr.net/npm/dynamsoft-javascript-barcode@9.6.32/dist/"; -``` - -### Interact with the SDK - -#### Create a `BarcodeScanner` object - -You can use one of two classes ( `BarcodeScanner` and `BarcodeReader` ) to interact with the SDK. `BarcodeReader` is a low-level class that processes images directly. `BarcodeScanner` , on the other hand, inherits from `BarcodeReader` and provides high-level APIs and a built-in GUI to allow continuous barcode scanning on video frames. We'll focus on `BarcodeScanner` in this guide. - -To use the SDK, we first create a `BarcodeScanner` object. - -```javascript -Dynamsoft.DBR.BarcodeScanner.license = "YOUR-LICENSE-KEY"; -let scanner = null; -try { - scanner = await Dynamsoft.DBR.BarcodeScanner.createInstance(); -} catch (ex) { - console.error(ex); -} -``` - -Tip: When creating a `BarcodeScanner` object within a function which may be called more than once, it's best to use a "helper" variable to avoid double creation such as `pScanner` in the following code - -```javascript -Dynamsoft.DBR.BarcodeScanner.license = "YOUR-LICENSE-KEY"; -let pScanner = null; -document.getElementById('btn-scan').addEventListener('click', async () => { - try { - const scanner = await (pScanner = pScanner || Dynamsoft.DBR.BarcodeScanner.createInstance()); - } catch (ex) { - console.error(ex); - } -}); -``` - -#### Customize the `BarcodeScanner` Settings (optional) - -Let's take a look at the following code snippets: - -```javascript -// Sets which camera and what resolution to use -let allCameras = await scanner.getAllCameras(); -await scanner.setCurrentCamera(allCameras[0].deviceId); -await scanner.setResolution(1280, 720); -``` - -```javascript -// Sets up the scanner behavior -let scanSettings = await scanner.getScanSettings(); -// Disregards duplicated results found in a specified time period (in milliseconds). -scanSettings.duplicateForgetTime = 5000; // The default is 3000 -// Sets a scan interval in milliseconds so the SDK may release the CPU from time to time. -// (setting this value larger is a simple way to save battery power and reduce device heating). -scanSettings.intervalTime = 100; // The default is 0. -// Sets captureAndDecodeInParallel to false, which tells the SDK not to acquire the next frame while decoding the first. -// This is another way to save battery power and is recommended on low-end phones. However, it does slow down the decoding speed. -scanSettings.captureAndDecodeInParallel = false; // The default is true. -await scanner.updateScanSettings(scanSettings); -``` - -```javascript -// Uses one of the built-in RuntimeSetting templates: "single" (decode a single barcode, the default mode), "speed", "balance", "coverage", "dense" and "distance" -await scanner.updateRuntimeSettings("speed"); - -// Makes changes to the template. The code below demonstrates how to specify enabled symbologies -let runtimeSettings = await scanner.getRuntimeSettings(); -runtimeSettings.barcodeFormatIds = Dynamsoft.DBR.EnumBarcodeFormat.BF_ONED | Dynamsoft.DBR.EnumBarcodeFormat.BF_QR_CODE; -await scanner.updateRuntimeSettings(runtimeSettings); -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/yfkcajxz/) - -As you can see from the above code snippets, there are three types of configurations: - -- Customize the data source: This configuration includes which camera to use, the preferred resolution, etc. Learn more here. - -- `get/updateScanSettings`: Configures the behavior of the scanner which includes `duplicateForgetTime` and `intervalTime`, etc. - -- `get/updateRuntimeSettings`: Configures the decode engine with either a built-in template or a comprehensive `RuntimeSettings` object. For example, the following uses the built-in "speed" settings with updated `localizationModes`. - - ```javascript - await barcodeScanner.updateRuntimeSettings("speed"); - //await barcodeScanner.updateRuntimeSettings("balance"); //alternative - //await barcodeScanner.updateRuntimeSettings("coverage"); //alternative - let settings = await barcodeScanner.getRuntimeSettings(); - settings.localizationModes = [ - Dynamsoft.DBR.EnumLocalizationMode.LM_CONNECTED_BLOCKS, - Dynamsoft.DBR.EnumLocalizationMode.LM_SCAN_DIRECTLY, - Dynamsoft.DBR.EnumLocalizationMode.LM_LINES, 0, 0, 0, 0, 0 - ]; - await barcodeScanner.updateRuntimeSettings(settings); - ``` - - Try in [JSFiddle](https://jsfiddle.net/DynamsoftTeam/f24h8c1m/). - - See also [settings samples](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/parameter-settings.html?ver=9.6.32&utm_source=guide). - -> Find the full list of the runtime settings here. - -### Customize the UI (optional) - -The built-in UI of the `BarcodeScanner` object is defined in the file `dist/dbr.ui.html` . There are a few ways to customize it: - -#### Modify the file `dist/dbr.ui.html` directly - - This option is only possible when you [Host the SDK yourself](#host-the-sdk-yourself) instead of using a public CDN. - -#### Copy the file `dist/dbr.ui.html` to your application, modify it and use the the API `defaultUIElementURL` to set it as the default UI - - ```javascript - // This line only takes effect before the method `createInstance()` is called. - Dynamsoft.DBR.BarcodeScanner.defaultUIElementURL = "THE-URL-TO-THE-FILE"; - ``` - -#### Append the default UI element to your page, customize it before showing it - - ```html -
- ``` - - ```javascript - document.getElementById('div-ui-container').appendChild(scanner.getUIElement()); - document.getElementsByClassName('dce-btn-close')[0].hidden = true; // Hide the close button - ``` - -#### Build the UI element from scratch and connect it to the SDK with the API `setUIElement(HTMLElement)` - -1. **Embed the video** - - ```html -
-
-
- - ``` - - > 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` . - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/2jzeq1r6/) - -2. **[Optional] Add the camera list and resolution list** - - If the class names of the created select elements match the default class names, i.e. `dce-sel-camera` and `dce-sel-resolution` respectively, the SDK will automatically populate the lists and handle the camera/resolution switching. - - ```html -
-
-
-
- ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/nbj75vxu/) - - ```html -
- - -
-
-
- ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/25v08paf/) - - > By default, only 3 hard-coded resolutions (1920 x 1080, 1280 x 720,640 x 480) are populated as options. You can show a customized set of options by hardcoding them. - - ```html - - ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/tnfjks4q/) - - > Generally, you need to provide a resolution that the camera supports. However, in case a camera does not support the specified resolution, it usually uses the closest supported resolution. As a result, the selected resolution may not be the actual resolution. In this case, add an option with the class name `dce-opt-gotResolution` (as shown above) and the SDK will automatically use it to show the **actual resolution**. - - See the section of the Explore Features guide on [UI customization]({{site.features}}customize-the-ui.html?lang=js) to learn more. - -## API Documentation - -You can check out the detailed documentation about the APIs of the SDK at -[https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/?ver=9.6.32](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/?ver=9.6.32). - -## System Requirements - -DBR requires the following features to work: - -- Secure context (HTTPS deployment) - - When deploying your application / website for production, make sure to serve it via a secure HTTPS connection. This is required for two reasons - - - Access to the camera video stream is only granted in a security context. Most browsers impose this restriction. - > Some browsers like Chrome may grant the access for `http://127.0.0.1` and `http://localhost` or even for pages opened directly from the local disk (`file:///...`). This can be helpful for temporary development and test. - - - Dynamsoft License requires a secure context to work. - -- `WebAssembly`, `Blob`, `URL`/`createObjectURL`, `Web Workers` - - The above four features are required for the SDK to work. - -- `MediaDevices`/`getUserMedia` - - This API is only required for in-browser video streaming. If a browser does not support this API, the [Single Frame Mode](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/BarcodeScanner.html?ver=9.6.32&utm_source=guide#singleframemode) will be used automatically. If the API exists but doesn't work correctly, the Single Frame Mode can be used as an alternative way to access the camera. - -- `getSettings` - - This API inspects the video input which is a `MediaStreamTrack` object about its constrainable properties. - -The following table is a list of supported browsers based on the above requirements: - - Browser Name | Version - :-: | :-: - Chrome | v59+1 - Firefox | v52+ (v55+ on Android/iOS1) - Edge2 | v16+ - Safari3 | v11+ - - 1 iOS 14.3+ is required for camera video streaming in Chrome and Firefox or Apps using webviews. - - 2 On Edge, due to strict Same-origin policy, you must host the SDK files on the same domain as your web page. - - 3 Safari v11.x already has the required features, but it has many other issues, so we recommend v12+. - -Apart from the browsers, the operating systems may impose some limitations of their own that could restrict the use of the SDK. Browser compatibility ultimately depends on whether the browser on that particular operating system supports the features listed above. - -## How to Upgrade - -If you want to upgrade the SDK from an old version to a newer one, please see [how to upgrade](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/upgrade-guide/?ver=9.6.32&utm_source=guide). - -## Release Notes - -Learn about what are included in each release at [https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/release-notes/?ver=latest](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/release-notes/?ver=latest). - -## Next Steps - -Now that you have got the SDK integrated, you can choose to move forward in the following directions - -1. Check out the [Official Samples and Demo](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/index.html?ver=latest) -2. Learn how to make use of the [SDK features](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/user-guide/explore-features/index.html?ver=latest) -3. See how the SDK works in [Popular Use Cases](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/user-guide/use-cases/index.html?ver=latest) diff --git a/programming-old/javascript/user-guide/index-v9.6.33.md b/programming-old/javascript/user-guide/index-v9.6.33.md deleted file mode 100644 index 8dcafbf4..00000000 --- a/programming-old/javascript/user-guide/index-v9.6.33.md +++ /dev/null @@ -1,511 +0,0 @@ ---- -layout: default-layout -title: v9.6.33 User Guide - Dynamsoft Barcode Reader JavaScript Edition -description: This is the user guide of Dynamsoft Barcode Reader JavaScript SDK. -keywords: user guide, javascript, js -breadcrumbText: User Guide -noTitleIndex: true -needGenerateH3Content: true -needAutoGenerateSidebar: true -permalink: /programming/javascript/user-guide/index-v9.6.33.html -schema: schemas/dynamsoft-facilitates-mit-research-schema.json ---- - - - -# Barcode Reader for Your Website - User Guide - -[Dynamsoft Barcode Reader JavaScript Edition](https://www.dynamsoft.com/barcode-reader/sdk-javascript/) (DBR-JS) is equipped with industry-leading algorithms for exceptional speed, accuracy and read rates in barcode reading. Using its well-designed API, you can turn your web page into a barcode scanner with just a few lines of code. - -![version](https://img.shields.io/npm/v/dynamsoft-javascript-barcode.svg) -![downloads](https://img.shields.io/npm/dm/dynamsoft-javascript-barcode.svg) -![jsdelivr](https://img.shields.io/jsdelivr/npm/hm/dynamsoft-javascript-barcode.svg) -![vulnerabilities](https://img.shields.io/snyk/vulnerabilities/npm/dynamsoft-javascript-barcode.svg) - -Once the DBR-JS SDK gets integrated into your web page, your users can access a camera via the browser and read barcodes directly from its video input. - - - -In this guide, you will learn step by step on how to integrate the DBR-JS SDK into your website. - -Table of Contents - -- [Hello World - Simplest Implementation](#hello-world---simplest-implementation) - - [Understand the code](#understand-the-code) - - [Run the example](#run-the-example) -- [Building your own page](#building-your-own-page) - - [Include the SDK](#include-the-sdk) - - [Configure the SDK](#configure-the-sdk) - - [Interact with the SDK](#interact-with-the-sdk) - - [Customize the UI (optional)](#customize-the-ui-optional) -- [API Documentation](#api-documentation) -- [System Requirements](#system-requirements) -- [How to Upgrade](#how-to-upgrade) -- [Release Notes](#release-notes) -- [Next Steps](#next-steps) - -**Popular Examples** - -- Hello World - [Guide](#hello-world---simplest-implementation) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.33/1.hello-world/1.hello-world.html) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/1.hello-world.html?ver=9.6.33&utm_source=guide) -- Angular App - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/helloworld-angular.html?ver=9.6.33&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.33/1.hello-world/3.read-video-angular) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/3.read-video-angular/dist/hello-world/?ver=9.6.33&utm_source=guide) -- React App - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/helloworld-reactjs.html?ver=9.6.33&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.33/1.hello-world/4.read-video-react) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/4.read-video-react/build/?ver=9.6.33&utm_source=guide) -- Vue App - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/helloworld-vuejsv3.html?ver=9.6.33&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.33/1.hello-world/6.read-video-vue3) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/6.read-video-vue3/dist/?ver=9.6.33&utm_source=guide) -- PWA App - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/helloworld-pwa.html?ver=9.6.33&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.33/1.hello-world/10.read-video-pwa) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/1.hello-world/10.read-video-pwa/helloworld-pwa.html?ver=9.6.33&utm_source=guide) -- WebView in Android and iOS - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/v9.6.33/1.hello-world/14.read-video-webview) -- Read Driver Licenses - [Guide](https://www.dynamsoft.com/barcode-reader/docs/core/programming/usecases/scan-and-parse-AAMVA.html?ver=9.6.33&utm_source=guide&&lang=js) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.33/4.use-case/2.read-a-drivers-license.html) \| [Run](https://demo.dynamsoft.com/samples/dbr/js/4.use-case/2.read-a-drivers-license.html?ver=9.6.33&utm_source=guide) -- Fill A Form - [Guide](https://www.dynamsoft.com/barcode-reader/docs/core/programming/usecases/scan-barcodes-as-input.html?lang=js&&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.33/4.use-case/1.fill-a-form-with-barcode-reading.html) \| [Run](https://demo.dynamsoft.com/samples/dbr/js/4.use-case/1.fill-a-form-with-barcode-reading.html?ver=9.6.33&utm_source=guide) -- Show result information on the video - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/main/4.use-case/3.show-result-texts-on-the-video.html) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/4.use-case/3.show-result-texts-on-the-video.html?ver=9.6.33&utm_source=guide) -- Debug Camera and Collect Video Frame - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/debug.html?lang=js&&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.33/5.others/debug) - -You can also: - -- Try the Official Demo - [Run](https://demo.dynamsoft.com/barcode-reader-js/?ver=9.6.33&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-demo/) -- Try Online Examples - [Run](https://demo.dynamsoft.com/Samples/DBR/JS/index.html?ver=9.6.33&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/v9.6.33/) - -## Hello World - Simplest Implementation - -Let's start with the "Hello World" example of the DBR-JS SDK which demonstrates how to use the minimum code to enable a web page to read barcodes from a live video stream. - -- Basic Requirements - - Internet connection - - [A supported browser](#system-requirements) - - Camera access - -### Understand the code - -The complete code of the "Hello World" example is shown below - -```html - - - - - - - - - -``` - -

- - Code in Github - -   - - Run via JSFiddle - -   - - Run in Dynamsoft - -

- ------ - -#### About the code - -- The DBR-JS SDK is included in the code via the **jsDelivr** CDN. - -> In some rare cases, you might not be able to access the CDN. If this happens, you can use [https://download2.dynamsoft.com/dbr/dynamsoft-barcode-reader-js/dynamsoft-barcode-reader-js-9.6.33/dist/dbr.js](https://download2.dynamsoft.com/dbr/dynamsoft-barcode-reader-js/dynamsoft-barcode-reader-js-9.6.33/dist/dbr.js) for the test. However, please DO NOT use CDN of `download2.dynamsoft.com` in your production application because it is temporary. Instead, you can try [hosting the SDK yourself](#host-the-sdk-yourself). - -- `license`: This property specifies a license key. Note that the license "DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9" used in this example is an online license and requires network connection to work. Read more on [Specify the license](#specify-the-license). - -- `createInstance()`: This method creates a `BarcodeScanner` object. This object can read barcodes directly from a video input with the help of its interactive UI (hidden by default) and the MediaDevices interface. - -- `onFrameRead`: This event is triggered every time the SDK finishes scanning a video frame. The `results` object contains all the barcode results that the SDK have found on this frame. In this example, we print the results to the browser console. - -- `onUniqueRead`: This event is triggered when the SDK finds a new barcode, which is not a duplicate among multiple frames. `txt` holds the barcode text value while `result` is an object that holds details of the barcode. In this example, an alert will be displayed for this new barcode. - -- `show()`: This method brings up the built-in UI of the `BarcodeScanner` object and starts scanning. - -### Run the example - -You can run the example deployed to the Dynamsoft Demo Server or test it with JSFiddle code editor. You will be asked to allow access to your camera, after which the video will be displayed on the page. After that, you can point the camera at a barcode to read it. - -When a barcode is decoded, you will see the result text pop up and the barcode location will be highlighted in the video feed. - -Alternatively, you can make a local test simply by taking the code in step 1, pasting it in a file with the name "hello-world.html" and open it in a browser. - -*Note*: - -If you open the web page as `file:///` or `http://` , the camera may not work correctly because the API getUserMedia usually requires HTTPS to access the camera. - -To make sure your web application can access the camera, please configure your web server to support HTTPS. The following links may help. - -1. NGINX: Configuring HTTPS servers -2. IIS: Create a Self Signed Certificate in IIS -3. Tomcat: Setting Up SSL on Tomcat in 5 minutes -4. Node.js: npm tls - -If the test doesn't go as expected, you can [contact us](https://www.dynamsoft.com/contact/?ver=9.6.33&utm_source=guide). - -## Building your own page - -### Include the SDK - -#### Use a public CDN - -The simplest way to include the SDK is to use either the [jsDelivr](https://jsdelivr.com/) or [UNPKG](https://unpkg.com/) CDN. The "hello world" example above uses **jsDelivr**. - -- jsDelivr - - ```html - - ``` - -- UNPKG - - ```html - - ``` - -#### Host the SDK yourself - -Besides using the public CDN, you can also download the SDK and host its files on your own server or a commercial CDN before including it in your application. - -Options to download the SDK: - -- From the website - - Download the JavaScript Package - -- yarn - - ```cmd - yarn add dynamsoft-javascript-barcode - ``` - -- npm - - ```cmd - npm install dynamsoft-javascript-barcode --save - ``` - -Depending on how you downloaded the SDK and how you intend to use it, you can typically include it like this: - -```html - -``` - -or - -```html - -``` - -or - -```typescript -import { BarcodeScanner } from 'dynamsoft-javascript-barcode'; -``` - -**NOTE** - -* Some older web application servers do not set `.wasm` mimetype as `application/wasm`. Upgrade your web application servers, or define the mimetype yourselves: - * [Apache](https://developer.mozilla.org/en-US/docs/Learn/Server-side/Apache_Configuration_htaccess#media_types_and_character_encodings) - * [IIS](https://docs.microsoft.com/en-us/iis/configuration/system.webserver/staticcontent/mimemap) - * [Nginx](https://www.nginx.com/resources/wiki/start/topics/examples/full/#mime-types) - -* To work properly, the SDK requires a few engine files, which are relatively large and may take quite a few seconds to download. We recommend that you set a longer cache time for these engine files, to maximize the performance of your web application. - - ```cmd - Cache-Control: max-age=31536000 - ``` - - Reference: [Cache-Control](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control). - -### Configure the SDK - -Before using the SDK, you need to configure a few things. - -#### Specify the license - -The SDK requires a license to work, use the API `license` to specify a license key. - -```javascript -Dynamsoft.DBR.BarcodeScanner.license = "YOUR-LICENSE-KEY"; -``` - -To test the SDK, you can request a 30-day trial license via the Request a Trial License link. - -> If you register a Dynamsoft account and download the SDK from the official website, Dynamsoft will automatically generate a 30-day trial license for you, and put the license key into all the samples attached to the SDK. - -#### Specify the location of the "engine" files - -This is usually only required with frameworks like Angular or React, etc. where dbr.js is compiled into another file. - -The purpose is to tell the SDK where to find the engine files (\*.worker.js, \*.wasm.js and \*.wasm, etc.). The API is called `engineResourcePath`: - -```javascript -//The following code uses the jsDelivr CDN, feel free to change it to your own location of these files -Dynamsoft.DBR.BarcodeScanner.engineResourcePath = "https://cdn.jsdelivr.net/npm/dynamsoft-javascript-barcode@9.6.33/dist/"; -``` - -### Interact with the SDK - -#### Create a `BarcodeScanner` object - -You can use one of two classes ( `BarcodeScanner` and `BarcodeReader` ) to interact with the SDK. `BarcodeReader` is a low-level class that processes images directly. `BarcodeScanner` , on the other hand, inherits from `BarcodeReader` and provides high-level APIs and a built-in GUI to allow continuous barcode scanning on video frames. We'll focus on `BarcodeScanner` in this guide. - -To use the SDK, we first create a `BarcodeScanner` object. - -```javascript -Dynamsoft.DBR.BarcodeScanner.license = "YOUR-LICENSE-KEY"; -let scanner = null; -try { - scanner = await Dynamsoft.DBR.BarcodeScanner.createInstance(); -} catch (ex) { - console.error(ex); -} -``` - -Tip: When creating a `BarcodeScanner` object within a function which may be called more than once, it's best to use a "helper" variable to avoid double creation such as `pScanner` in the following code - -```javascript -Dynamsoft.DBR.BarcodeScanner.license = "YOUR-LICENSE-KEY"; -let pScanner = null; -document.getElementById('btn-scan').addEventListener('click', async () => { - try { - const scanner = await (pScanner = pScanner || Dynamsoft.DBR.BarcodeScanner.createInstance()); - } catch (ex) { - console.error(ex); - } -}); -``` - -#### Customize the `BarcodeScanner` Settings (optional) - -Let's take a look at the following code snippets: - -```javascript -// Sets which camera and what resolution to use -let allCameras = await scanner.getAllCameras(); -await scanner.setCurrentCamera(allCameras[0].deviceId); -await scanner.setResolution(1280, 720); -``` - -```javascript -// Sets up the scanner behavior -let scanSettings = await scanner.getScanSettings(); -// Disregards duplicated results found in a specified time period (in milliseconds). -scanSettings.duplicateForgetTime = 5000; // The default is 3000 -// Sets a scan interval in milliseconds so the SDK may release the CPU from time to time. -// (setting this value larger is a simple way to save battery power and reduce device heating). -scanSettings.intervalTime = 100; // The default is 0. -// Sets captureAndDecodeInParallel to false, which tells the SDK not to acquire the next frame while decoding the first. -// This is another way to save battery power and is recommended on low-end phones. However, it does slow down the decoding speed. -scanSettings.captureAndDecodeInParallel = false; // The default is true. -await scanner.updateScanSettings(scanSettings); -``` - -```javascript -// Uses one of the built-in RuntimeSetting templates: "single" (decode a single barcode, the default mode), "speed", "balance", "coverage", "dense" and "distance" -await scanner.updateRuntimeSettings("speed"); - -// Makes changes to the template. The code below demonstrates how to specify enabled symbologies -let runtimeSettings = await scanner.getRuntimeSettings(); -runtimeSettings.barcodeFormatIds = Dynamsoft.DBR.EnumBarcodeFormat.BF_ONED | Dynamsoft.DBR.EnumBarcodeFormat.BF_QR_CODE; -await scanner.updateRuntimeSettings(runtimeSettings); -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/yfkcajxz/) - -As you can see from the above code snippets, there are three types of configurations: - -- Customize the data source: This configuration includes which camera to use, the preferred resolution, etc. Learn more here. - -- `get/updateScanSettings`: Configures the behavior of the scanner which includes `duplicateForgetTime` and `intervalTime`, etc. - -- `get/updateRuntimeSettings`: Configures the decode engine with either a built-in template or a comprehensive `RuntimeSettings` object. For example, the following uses the built-in "speed" settings with updated `localizationModes`. - - ```javascript - await barcodeScanner.updateRuntimeSettings("speed"); - //await barcodeScanner.updateRuntimeSettings("balance"); //alternative - //await barcodeScanner.updateRuntimeSettings("coverage"); //alternative - let settings = await barcodeScanner.getRuntimeSettings(); - settings.localizationModes = [ - Dynamsoft.DBR.EnumLocalizationMode.LM_CONNECTED_BLOCKS, - Dynamsoft.DBR.EnumLocalizationMode.LM_SCAN_DIRECTLY, - Dynamsoft.DBR.EnumLocalizationMode.LM_LINES, 0, 0, 0, 0, 0 - ]; - await barcodeScanner.updateRuntimeSettings(settings); - ``` - - Try in [JSFiddle](https://jsfiddle.net/DynamsoftTeam/f24h8c1m/). - - See also [settings samples](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/parameter-settings.html?ver=9.6.33&utm_source=guide). - -> Find the full list of the runtime settings here. - -### Customize the UI (optional) - -The built-in UI of the `BarcodeScanner` object is defined in the file `dist/dbr.ui.html` . There are a few ways to customize it: - -#### Modify the file `dist/dbr.ui.html` directly - - This option is only possible when you [Host the SDK yourself](#host-the-sdk-yourself) instead of using a public CDN. - -#### Copy the file `dist/dbr.ui.html` to your application, modify it and use the the API `defaultUIElementURL` to set it as the default UI - - ```javascript - // This line only takes effect before the method `createInstance()` is called. - Dynamsoft.DBR.BarcodeScanner.defaultUIElementURL = "THE-URL-TO-THE-FILE"; - ``` - -#### Append the default UI element to your page, customize it before showing it - - ```html -
- ``` - - ```javascript - document.getElementById('div-ui-container').appendChild(scanner.getUIElement()); - document.getElementsByClassName('dce-btn-close')[0].hidden = true; // Hide the close button - ``` - -#### Build the UI element from scratch and connect it to the SDK with the API `setUIElement(HTMLElement)` - -1. **Embed the video** - - ```html -
-
-
- - ``` - - > 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` . - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/2jzeq1r6/) - -2. **[Optional] Add the camera list and resolution list** - - If the class names of the created select elements match the default class names, i.e. `dce-sel-camera` and `dce-sel-resolution` respectively, the SDK will automatically populate the lists and handle the camera/resolution switching. - - ```html -
-
-
-
- ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/nbj75vxu/) - - ```html -
- - -
-
-
- ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/25v08paf/) - - > By default, only 3 hard-coded resolutions (1920 x 1080, 1280 x 720,640 x 480) are populated as options. You can show a customized set of options by hardcoding them. - - ```html - - ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/tnfjks4q/) - - > Generally, you need to provide a resolution that the camera supports. However, in case a camera does not support the specified resolution, it usually uses the closest supported resolution. As a result, the selected resolution may not be the actual resolution. In this case, add an option with the class name `dce-opt-gotResolution` (as shown above) and the SDK will automatically use it to show the **actual resolution**. - - See the section of the Explore Features guide on [UI customization]({{site.features}}customize-the-ui.html?lang=js) to learn more. - -## API Documentation - -You can check out the detailed documentation about the APIs of the SDK at -[https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/?ver=9.6.33](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/?ver=9.6.33). - -## System Requirements - -DBR requires the following features to work: - -- Secure context (HTTPS deployment) - - When deploying your application / website for production, make sure to serve it via a secure HTTPS connection. This is required for two reasons - - - Access to the camera video stream is only granted in a security context. Most browsers impose this restriction. - > Some browsers like Chrome may grant the access for `http://127.0.0.1` and `http://localhost` or even for pages opened directly from the local disk (`file:///...`). This can be helpful for temporary development and test. - - - Dynamsoft License requires a secure context to work. - -- `WebAssembly`, `Blob`, `URL`/`createObjectURL`, `Web Workers` - - The above four features are required for the SDK to work. - -- `MediaDevices`/`getUserMedia` - - This API is only required for in-browser video streaming. If a browser does not support this API, the [Single Frame Mode](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/BarcodeScanner.html?ver=9.6.33&utm_source=guide#singleframemode) will be used automatically. If the API exists but doesn't work correctly, the Single Frame Mode can be used as an alternative way to access the camera. - -- `getSettings` - - This API inspects the video input which is a `MediaStreamTrack` object about its constrainable properties. - -The following table is a list of supported browsers based on the above requirements: - - Browser Name | Version - :-: | :-: - Chrome | v59+1 - Firefox | v52+ (v55+ on Android/iOS1) - Edge2 | v16+ - Safari3 | v11+ - - 1 iOS 14.3+ is required for camera video streaming in Chrome and Firefox or Apps using webviews. - - 2 On Edge, due to strict Same-origin policy, you must host the SDK files on the same domain as your web page. - - 3 Safari v11.x already has the required features, but it has many other issues, so we recommend v12+. - -Apart from the browsers, the operating systems may impose some limitations of their own that could restrict the use of the SDK. Browser compatibility ultimately depends on whether the browser on that particular operating system supports the features listed above. - -## How to Upgrade - -If you want to upgrade the SDK from an old version to a newer one, please see [how to upgrade](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/upgrade-guide/?ver=9.6.33&utm_source=guide). - -## Release Notes - -Learn about what are included in each release at [https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/release-notes/?ver=latest](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/release-notes/?ver=latest). - -## Next Steps - -Now that you have got the SDK integrated, you can choose to move forward in the following directions - -1. Check out the [Official Samples and Demo](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/index.html?ver=latest) -2. Learn how to make use of the [SDK features](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/user-guide/explore-features/index.html?ver=latest) -3. See how the SDK works in [Popular Use Cases](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/user-guide/use-cases/index.html?ver=latest) diff --git a/programming-old/javascript/user-guide/index-v9.6.40.md b/programming-old/javascript/user-guide/index-v9.6.40.md deleted file mode 100644 index 6acc2651..00000000 --- a/programming-old/javascript/user-guide/index-v9.6.40.md +++ /dev/null @@ -1,512 +0,0 @@ ---- -layout: default-layout -title: v9.6.40 User Guide - Dynamsoft Barcode Reader JavaScript Edition -description: This is the user guide of Dynamsoft Barcode Reader JavaScript SDK. -keywords: user guide, javascript, js -breadcrumbText: User Guide -noTitleIndex: true -needGenerateH3Content: true -needAutoGenerateSidebar: true -permalink: /programming/javascript/user-guide/index-v9.6.40.html -schema: schemas/dynamsoft-facilitates-mit-research-schema.json ---- - - - -# Barcode Reader for Your Website - User Guide - -[Dynamsoft Barcode Reader JavaScript Edition](https://www.dynamsoft.com/barcode-reader/sdk-javascript/) (DBR-JS) is equipped with industry-leading algorithms for exceptional speed, accuracy and read rates in barcode reading. Using its well-designed API, you can turn your web page into a barcode scanner with just a few lines of code. - -![version](https://img.shields.io/npm/v/dynamsoft-javascript-barcode.svg) -![downloads](https://img.shields.io/npm/dm/dynamsoft-javascript-barcode.svg) -![jsdelivr](https://img.shields.io/jsdelivr/npm/hm/dynamsoft-javascript-barcode.svg) -![vulnerabilities](https://img.shields.io/snyk/vulnerabilities/npm/dynamsoft-javascript-barcode.svg) - -Once the DBR-JS SDK gets integrated into your web page, your users can access a camera via the browser and read barcodes directly from its video input. - - - -In this guide, you will learn step by step on how to integrate the DBR-JS SDK into your website. - -Table of Contents - -- [Hello World - Simplest Implementation](#hello-world---simplest-implementation) - - [Understand the code](#understand-the-code) - - [Run the example](#run-the-example) -- [Building your own page](#building-your-own-page) - - [Include the SDK](#include-the-sdk) - - [Configure the SDK](#configure-the-sdk) - - [Interact with the SDK](#interact-with-the-sdk) - - [Customize the UI (optional)](#customize-the-ui-optional) -- [API Documentation](#api-documentation) -- [System Requirements](#system-requirements) -- [How to Upgrade](#how-to-upgrade) -- [Release Notes](#release-notes) -- [Next Steps](#next-steps) - -**Popular Examples** - -- Hello World - [Guide](#hello-world---simplest-implementation) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.40/1.hello-world/1.hello-world.html) -- Angular App - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/helloworld-angular.html?ver=9.6.40&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.40/1.hello-world/3.read-video-angular) -- React App - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/helloworld-reactjs.html?ver=9.6.40&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.40/1.hello-world/4.read-video-react) -- Vue App - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/helloworld-vuejsv3.html?ver=9.6.40&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.40/1.hello-world/6.read-video-vue3) -- PWA App - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/helloworld-pwa.html?ver=9.6.40&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.40/1.hello-world/10.read-video-pwa) -- WebView in Android and iOS - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/v9.6.40/1.hello-world/14.read-video-webview) -- Read Driver Licenses - [Guide](https://www.dynamsoft.com/barcode-reader/docs/core/programming/usecases/scan-and-parse-AAMVA.html?ver=9.6.40&utm_source=guide&&lang=js) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.40/4.use-case/2.read-a-drivers-license.html) -- Fill A Form - [Guide](https://www.dynamsoft.com/barcode-reader/docs/core/programming/usecases/scan-barcodes-as-input.html?lang=js&&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.40/4.use-case/1.fill-a-form-with-barcode-reading.html) -- Show result information on the video - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/main/4.use-case/3.show-result-texts-on-the-video.html) -- Debug Camera and Collect Video Frame - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/debug.html?lang=js&&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.40/5.others/debug) - -You can also: - -- Try the Official Demo - [Run](https://demo.dynamsoft.com/barcode-reader-js/?ver=9.6.40&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-demo/) -- Try Online Examples - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/v9.6.40/) - -## Hello World - Simplest Implementation - -Let's start with the "Hello World" example of the DBR-JS SDK which demonstrates how to use the minimum code to enable a web page to read barcodes from a live video stream. - -- Basic Requirements - - Internet connection - - [A supported browser](#system-requirements) - - Camera access - -### Understand the code - -The complete code of the "Hello World" example is shown below - -```html - - - - - - - - - -``` - -

- - Code in Github - -   - - Run via JSFiddle - - -

- ------ - -#### About the code - -- The DBR-JS SDK is included in the code via the **jsDelivr** CDN. - -> In some rare cases, you might not be able to access the CDN. If this happens, you can use [https://download2.dynamsoft.com/dbr/dynamsoft-barcode-reader-js/dynamsoft-barcode-reader-js-9.6.40/dist/dbr.js](https://download2.dynamsoft.com/dbr/dynamsoft-barcode-reader-js/dynamsoft-barcode-reader-js-9.6.40/dist/dbr.js) for the test. However, please DO NOT use CDN of `download2.dynamsoft.com` in your production application because it is temporary. Instead, you can try [hosting the SDK yourself](#host-the-sdk-yourself). - -- `license`: This property specifies a license key. Note that the license "DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9" used in this example is an online license and requires network connection to work. Read more on [Specify the license](#specify-the-license). - -- `createInstance()`: This method creates a `BarcodeScanner` object. This object can read barcodes directly from a video input with the help of its interactive UI (hidden by default) and the MediaDevices interface. - -- `onFrameRead`: This event is triggered every time the SDK finishes scanning a video frame. The `results` object contains all the barcode results that the SDK have found on this frame. In this example, we print the results to the browser console. - -- `onUniqueRead`: This event is triggered when the SDK finds a new barcode, which is not a duplicate among multiple frames. `txt` holds the barcode text value while `result` is an object that holds details of the barcode. In this example, an alert will be displayed for this new barcode. - -- `show()`: This method brings up the built-in UI of the `BarcodeScanner` object and starts scanning. - -### Run the example - -You can run the example deployed to the Dynamsoft Demo Server or test it with JSFiddle code editor. You will be asked to allow access to your camera, after which the video will be displayed on the page. After that, you can point the camera at a barcode to read it. - -When a barcode is decoded, you will see the result text pop up and the barcode location will be highlighted in the video feed. - -Alternatively, you can make a local test simply by taking the code in step 1, pasting it in a file with the name "hello-world.html" and open it in a browser. - -*Note*: - -If you open the web page as `file:///` or `http://` , the camera may not work correctly because the API getUserMedia usually requires HTTPS to access the camera. - -To make sure your web application can access the camera, please configure your web server to support HTTPS. The following links may help. - -1. NGINX: Configuring HTTPS servers -2. IIS: Create a Self Signed Certificate in IIS -3. Tomcat: Setting Up SSL on Tomcat in 5 minutes -4. Node.js: npm tls - -If the test doesn't go as expected, you can [contact us](https://www.dynamsoft.com/contact/?ver=9.6.40&utm_source=guide). - -## Building your own page - -### Include the SDK - -#### Use a public CDN - -The simplest way to include the SDK is to use either the [jsDelivr](https://jsdelivr.com/) or [UNPKG](https://unpkg.com/) CDN. The "hello world" example above uses **jsDelivr**. - -- jsDelivr - - ```html - - ``` - -- UNPKG - - ```html - - ``` - -#### Host the SDK yourself - -Besides using the public CDN, you can also download the SDK and host its files on your own server or a commercial CDN before including it in your application. - -Options to download the SDK: - -- From the website - - Download the JavaScript Package - -- yarn - - ```cmd - yarn add dynamsoft-javascript-barcode - ``` - -- npm - - ```cmd - npm install dynamsoft-javascript-barcode --save - ``` - -Depending on how you downloaded the SDK and how you intend to use it, you can typically include it like this: - -```html - -``` - -or - -```html - -``` - -or - -```typescript -import { BarcodeScanner } from 'dynamsoft-javascript-barcode'; -``` - -**NOTE** - -* Some older web application servers do not set `.wasm` mimetype as `application/wasm`. Upgrade your web application servers, or define the mimetype yourselves: - * [Apache](https://developer.mozilla.org/en-US/docs/Learn/Server-side/Apache_Configuration_htaccess#media_types_and_character_encodings) - * [IIS](https://docs.microsoft.com/en-us/iis/configuration/system.webserver/staticcontent/mimemap) - * [Nginx](https://www.nginx.com/resources/wiki/start/topics/examples/full/#mime-types) - -* To work properly, the SDK requires a few engine files, which are relatively large and may take quite a few seconds to download. We recommend that you set a longer cache time for these engine files, to maximize the performance of your web application. - - ```cmd - Cache-Control: max-age=31536000 - ``` - - Reference: [Cache-Control](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control). - -### Configure the SDK - -Before using the SDK, you need to configure a few things. - -#### Specify the license - -The SDK requires a license to work, use the API `license` to specify a license key. - -```javascript -Dynamsoft.DBR.BarcodeScanner.license = "YOUR-LICENSE-KEY"; -``` - -To test the SDK, you can request a 30-day trial license via the Request a Trial License link. - -> If you register a Dynamsoft account and download the SDK from the official website, Dynamsoft will automatically generate a 30-day trial license for you, and put the license key into all the samples attached to the SDK. - -#### Specify the location of the "engine" files - -This is usually only required with frameworks like Angular or React, etc. where dbr.js is compiled into another file. - -The purpose is to tell the SDK where to find the engine files (\*.worker.js, \*.wasm.js and \*.wasm, etc.). The API is called `engineResourcePath`: - -```javascript -//The following code uses the jsDelivr CDN, feel free to change it to your own location of these files -Dynamsoft.DBR.BarcodeScanner.engineResourcePath = "https://cdn.jsdelivr.net/npm/dynamsoft-javascript-barcode@9.6.40/dist/"; -``` - -### Interact with the SDK - -#### Create a `BarcodeScanner` object - -You can use one of two classes ( `BarcodeScanner` and `BarcodeReader` ) to interact with the SDK. `BarcodeReader` is a low-level class that processes images directly. `BarcodeScanner` , on the other hand, inherits from `BarcodeReader` and provides high-level APIs and a built-in GUI to allow continuous barcode scanning on video frames. We'll focus on `BarcodeScanner` in this guide. - -To use the SDK, we first create a `BarcodeScanner` object. - -```javascript -Dynamsoft.DBR.BarcodeScanner.license = "YOUR-LICENSE-KEY"; -let scanner = null; -try { - scanner = await Dynamsoft.DBR.BarcodeScanner.createInstance(); -} catch (ex) { - console.error(ex); -} -``` - -Tip: When creating a `BarcodeScanner` object within a function which may be called more than once, it's best to use a "helper" variable to avoid double creation such as `pScanner` in the following code - -```javascript -Dynamsoft.DBR.BarcodeScanner.license = "YOUR-LICENSE-KEY"; -let pScanner = null; -document.getElementById('btn-scan').addEventListener('click', async () => { - try { - const scanner = await (pScanner = pScanner || Dynamsoft.DBR.BarcodeScanner.createInstance()); - } catch (ex) { - console.error(ex); - } -}); -``` - -#### Customize the `BarcodeScanner` Settings (optional) - -Let's take a look at the following code snippets: - -```javascript -// Sets which camera and what resolution to use -let allCameras = await scanner.getAllCameras(); -await scanner.setCurrentCamera(allCameras[0].deviceId); -await scanner.setResolution(1280, 720); -``` - -```javascript -// Sets up the scanner behavior -let scanSettings = await scanner.getScanSettings(); -// Disregards duplicated results found in a specified time period (in milliseconds). -scanSettings.duplicateForgetTime = 5000; // The default is 3000 -// Sets a scan interval in milliseconds so the SDK may release the CPU from time to time. -// (setting this value larger is a simple way to save battery power and reduce device heating). -scanSettings.intervalTime = 100; // The default is 0. -// Sets captureAndDecodeInParallel to false, which tells the SDK not to acquire the next frame while decoding the first. -// This is another way to save battery power and is recommended on low-end phones. However, it does slow down the decoding speed. -scanSettings.captureAndDecodeInParallel = false; // The default is true. -await scanner.updateScanSettings(scanSettings); -``` - -```javascript -// Uses one of the built-in RuntimeSetting templates: "single" (decode a single barcode, the default mode), "speed", "balance", "coverage", "dense" and "distance" -await scanner.updateRuntimeSettings("speed"); - -// Makes changes to the template. The code below demonstrates how to specify enabled symbologies -let runtimeSettings = await scanner.getRuntimeSettings(); -runtimeSettings.barcodeFormatIds = Dynamsoft.DBR.EnumBarcodeFormat.BF_ONED | Dynamsoft.DBR.EnumBarcodeFormat.BF_QR_CODE; -await scanner.updateRuntimeSettings(runtimeSettings); -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/yfkcajxz/) - -As you can see from the above code snippets, there are three types of configurations: - -- Customize the data source: This configuration includes which camera to use, the preferred resolution, etc. Learn more here. - -- `get/updateScanSettings`: Configures the behavior of the scanner which includes `duplicateForgetTime` and `intervalTime`, etc. - -- `get/updateRuntimeSettings`: Configures the decode engine with either a built-in template or a comprehensive `RuntimeSettings` object. For example, the following uses the built-in "speed" settings with updated `localizationModes`. - - ```javascript - await barcodeScanner.updateRuntimeSettings("speed"); - //await barcodeScanner.updateRuntimeSettings("balance"); //alternative - //await barcodeScanner.updateRuntimeSettings("coverage"); //alternative - let settings = await barcodeScanner.getRuntimeSettings(); - settings.localizationModes = [ - Dynamsoft.DBR.EnumLocalizationMode.LM_CONNECTED_BLOCKS, - Dynamsoft.DBR.EnumLocalizationMode.LM_SCAN_DIRECTLY, - Dynamsoft.DBR.EnumLocalizationMode.LM_LINES, 0, 0, 0, 0, 0 - ]; - await barcodeScanner.updateRuntimeSettings(settings); - ``` - - Try in [JSFiddle](https://jsfiddle.net/DynamsoftTeam/f24h8c1m/). - - See also [settings samples](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/parameter-settings.html?ver=9.6.40&utm_source=guide). - -> Find the full list of the runtime settings here. - -### Customize the UI (optional) - -The built-in UI of the `BarcodeScanner` object is defined in the file `dist/dbr.ui.html` . There are a few ways to customize it: - -#### Modify the file `dist/dbr.ui.html` directly - - This option is only possible when you [Host the SDK yourself](#host-the-sdk-yourself) instead of using a public CDN. - -#### Copy the file `dist/dbr.ui.html` to your application, modify it and use the the API `defaultUIElementURL` to set it as the default UI - - ```javascript - // This line only takes effect before the method `createInstance()` is called. - Dynamsoft.DBR.BarcodeScanner.defaultUIElementURL = "THE-URL-TO-THE-FILE"; - ``` - -#### Append the default UI element to your page, customize it before showing it - - ```html -
- ``` - - ```javascript - document.getElementById('div-ui-container').appendChild(scanner.getUIElement()); - document.getElementsByClassName('dce-btn-close')[0].hidden = true; // Hide the close button - ``` - -#### Build the UI element from scratch and connect it to the SDK with the API `setUIElement(HTMLElement)` - -1. **Embed the video** - - ```html -
-
-
- - ``` - - > 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` . - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/2jzeq1r6/) - -2. **[Optional] Add the camera list and resolution list** - - If the class names of the created select elements match the default class names, i.e. `dce-sel-camera` and `dce-sel-resolution` respectively, the SDK will automatically populate the lists and handle the camera/resolution switching. - - ```html -
-
-
-
- ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/nbj75vxu/) - - ```html -
- - -
-
-
- ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/25v08paf/) - - > By default, only 3 hard-coded resolutions (1920 x 1080, 1280 x 720,640 x 480) are populated as options. You can show a customized set of options by hardcoding them. - - ```html - - ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/tnfjks4q/) - - > Generally, you need to provide a resolution that the camera supports. However, in case a camera does not support the specified resolution, it usually uses the closest supported resolution. As a result, the selected resolution may not be the actual resolution. In this case, add an option with the class name `dce-opt-gotResolution` (as shown above) and the SDK will automatically use it to show the **actual resolution**. - - See the section of the Explore Features guide on [UI customization]({{site.features}}customize-the-ui.html?lang=js) to learn more. - -## API Documentation - -You can check out the detailed documentation about the APIs of the SDK at -[https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/?ver=9.6.40](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/?ver=9.6.40). - -## System Requirements - -DBR requires the following features to work: - -- Secure context (HTTPS deployment) - - When deploying your application / website for production, make sure to serve it via a secure HTTPS connection. This is required for two reasons - - - Access to the camera video stream is only granted in a security context. Most browsers impose this restriction. - > Some browsers like Chrome may grant the access for `http://127.0.0.1` and `http://localhost` or even for pages opened directly from the local disk (`file:///...`). This can be helpful for temporary development and test. - - - Dynamsoft License requires a secure context to work. - -- `WebAssembly`, `Blob`, `URL`/`createObjectURL`, `Web Workers` - - The above four features are required for the SDK to work. - -- `MediaDevices`/`getUserMedia` - - This API is only required for in-browser video streaming. If a browser does not support this API, the [Single Frame Mode](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/BarcodeScanner.html?ver=9.6.40&utm_source=guide#singleframemode) will be used automatically. If the API exists but doesn't work correctly, the Single Frame Mode can be used as an alternative way to access the camera. - -- `getSettings` - - This API inspects the video input which is a `MediaStreamTrack` object about its constrainable properties. - -The following table is a list of supported browsers based on the above requirements: - - Browser Name | Version - :-: | :-: - Chrome | v59+1 - Firefox | v52+ (v55+ on Android/iOS1) - Edge2 | v16+ - Safari3 | v11+ - - 1 iOS 14.3+ is required for camera video streaming in Chrome and Firefox or Apps using webviews. - - 2 On Edge, due to strict Same-origin policy, you must host the SDK files on the same domain as your web page. - - 3 Safari v11.x already has the required features, but it has many other issues, so we recommend v12+. - -Apart from the browsers, the operating systems may impose some limitations of their own that could restrict the use of the SDK. Browser compatibility ultimately depends on whether the browser on that particular operating system supports the features listed above. - -## How to Upgrade - -If you want to upgrade the SDK from an old version to a newer one, please see [how to upgrade](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/upgrade-guide/?ver=9.6.40&utm_source=guide). - -## Release Notes - -Learn about what are included in each release at [https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/release-notes/?ver=latest](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/release-notes/?ver=latest). - -## Next Steps - -Now that you have got the SDK integrated, you can choose to move forward in the following directions - -1. Check out the [Official Samples and Demo](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/index.html?ver=latest) -2. Learn how to make use of the [SDK features](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/user-guide/explore-features/index.html?ver=latest) -3. See how the SDK works in [Popular Use Cases](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/user-guide/use-cases/index.html?ver=latest) diff --git a/programming-old/javascript/user-guide/index-v9.6.42.md b/programming-old/javascript/user-guide/index-v9.6.42.md deleted file mode 100644 index 8e1f62df..00000000 --- a/programming-old/javascript/user-guide/index-v9.6.42.md +++ /dev/null @@ -1,512 +0,0 @@ ---- -layout: default-layout -title: v9.6.42 User Guide - Dynamsoft Barcode Reader JavaScript Edition -description: This is the user guide of Dynamsoft Barcode Reader JavaScript SDK. -keywords: user guide, javascript, js -breadcrumbText: User Guide -noTitleIndex: true -needGenerateH3Content: true -needAutoGenerateSidebar: true -permalink: /programming/javascript/user-guide/index-v9.6.42.html -schema: schemas/dynamsoft-facilitates-mit-research-schema.json ---- - - - -# Barcode Reader for Your Website - User Guide - -[Dynamsoft Barcode Reader JavaScript Edition](https://www.dynamsoft.com/barcode-reader/sdk-javascript/) (DBR-JS) is equipped with industry-leading algorithms for exceptional speed, accuracy and read rates in barcode reading. Using its well-designed API, you can turn your web page into a barcode scanner with just a few lines of code. - -![version](https://img.shields.io/npm/v/dynamsoft-javascript-barcode.svg) -![downloads](https://img.shields.io/npm/dm/dynamsoft-javascript-barcode.svg) -![jsdelivr](https://img.shields.io/jsdelivr/npm/hm/dynamsoft-javascript-barcode.svg) -![vulnerabilities](https://img.shields.io/snyk/vulnerabilities/npm/dynamsoft-javascript-barcode.svg) - -Once the DBR-JS SDK gets integrated into your web page, your users can access a camera via the browser and read barcodes directly from its video input. - - - -In this guide, you will learn step by step on how to integrate the DBR-JS SDK into your website. - -Table of Contents - -- [Hello World - Simplest Implementation](#hello-world---simplest-implementation) - - [Understand the code](#understand-the-code) - - [Run the example](#run-the-example) -- [Building your own page](#building-your-own-page) - - [Include the SDK](#include-the-sdk) - - [Configure the SDK](#configure-the-sdk) - - [Interact with the SDK](#interact-with-the-sdk) - - [Customize the UI (optional)](#customize-the-ui-optional) -- [API Documentation](#api-documentation) -- [System Requirements](#system-requirements) -- [How to Upgrade](#how-to-upgrade) -- [Release Notes](#release-notes) -- [Next Steps](#next-steps) - -**Popular Examples** - -- Hello World - [Guide](#hello-world---simplest-implementation) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.42/1.hello-world/1.hello-world.html) -- Angular App - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/helloworld-angular.html?ver=9.6.42&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.42/1.hello-world/3.read-video-angular) -- React App - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/helloworld-reactjs.html?ver=9.6.42&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.42/1.hello-world/4.read-video-react) -- Vue App - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/helloworld-vuejsv3.html?ver=9.6.42&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.42/1.hello-world/6.read-video-vue3) -- PWA App - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/helloworld-pwa.html?ver=9.6.42&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.42/1.hello-world/10.read-video-pwa) -- WebView in Android and iOS - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/v9.6.42/1.hello-world/14.read-video-webview) -- Read Driver Licenses - [Guide](https://www.dynamsoft.com/barcode-reader/docs/core/programming/usecases/scan-and-parse-AAMVA.html?ver=9.6.42&utm_source=guide&&lang=js) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.42/4.use-case/2.read-a-drivers-license.html) -- Fill A Form - [Guide](https://www.dynamsoft.com/barcode-reader/docs/core/programming/usecases/scan-barcodes-as-input.html?lang=js&&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.42/4.use-case/1.fill-a-form-with-barcode-reading.html) -- Show result information on the video - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/main/4.use-case/3.show-result-texts-on-the-video.html) -- Debug Camera and Collect Video Frame - [Guide](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/debug.html?lang=js&&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v9.6.42/5.others/debug) - -You can also: - -- Try the Official Demo - [Run](https://demo.dynamsoft.com/barcode-reader-js/?ver=9.6.42&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-demo/) -- Try Online Examples - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/v9.6.42/) - -## Hello World - Simplest Implementation - -Let's start with the "Hello World" example of the DBR-JS SDK which demonstrates how to use the minimum code to enable a web page to read barcodes from a live video stream. - -- Basic Requirements - - Internet connection - - [A supported browser](#system-requirements) - - Camera access - -### Understand the code - -The complete code of the "Hello World" example is shown below - -```html - - - - - - - - - -``` - -

- - Code in Github - -   - - Run via JSFiddle - - -

- ------ - -#### About the code - -- The DBR-JS SDK is included in the code via the **jsDelivr** CDN. - -> In some rare cases, you might not be able to access the CDN. If this happens, you can use [https://download2.dynamsoft.com/dbr/dynamsoft-barcode-reader-js/dynamsoft-barcode-reader-js-9.6.42/dist/dbr.js](https://download2.dynamsoft.com/dbr/dynamsoft-barcode-reader-js/dynamsoft-barcode-reader-js-9.6.42/dist/dbr.js) for the test. However, please DO NOT use CDN of `download2.dynamsoft.com` in your production application because it is temporary. Instead, you can try [hosting the SDK yourself](#host-the-sdk-yourself). - -- `license`: This property specifies a license key. Note that the license "DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9" used in this example is an online license and requires network connection to work. Read more on [Specify the license](#specify-the-license). - -- `createInstance()`: This method creates a `BarcodeScanner` object. This object can read barcodes directly from a video input with the help of its interactive UI (hidden by default) and the MediaDevices interface. - -- `onFrameRead`: This event is triggered every time the SDK finishes scanning a video frame. The `results` object contains all the barcode results that the SDK have found on this frame. In this example, we print the results to the browser console. - -- `onUniqueRead`: This event is triggered when the SDK finds a new barcode, which is not a duplicate among multiple frames. `txt` holds the barcode text value while `result` is an object that holds details of the barcode. In this example, an alert will be displayed for this new barcode. - -- `show()`: This method brings up the built-in UI of the `BarcodeScanner` object and starts scanning. - -### Run the example - -You can run the example deployed to the Dynamsoft Demo Server or test it with JSFiddle code editor. You will be asked to allow access to your camera, after which the video will be displayed on the page. After that, you can point the camera at a barcode to read it. - -When a barcode is decoded, you will see the result text pop up and the barcode location will be highlighted in the video feed. - -Alternatively, you can make a local test simply by taking the code in step 1, pasting it in a file with the name "hello-world.html" and open it in a browser. - -*Note*: - -If you open the web page as `file:///` or `http://` , the camera may not work correctly because the API getUserMedia usually requires HTTPS to access the camera. - -To make sure your web application can access the camera, please configure your web server to support HTTPS. The following links may help. - -1. NGINX: Configuring HTTPS servers -2. IIS: Create a Self Signed Certificate in IIS -3. Tomcat: Setting Up SSL on Tomcat in 5 minutes -4. Node.js: npm tls - -If the test doesn't go as expected, you can [contact us](https://www.dynamsoft.com/contact/?ver=9.6.42&utm_source=guide). - -## Building your own page - -### Include the SDK - -#### Use a public CDN - -The simplest way to include the SDK is to use either the [jsDelivr](https://jsdelivr.com/) or [UNPKG](https://unpkg.com/) CDN. The "hello world" example above uses **jsDelivr**. - -- jsDelivr - - ```html - - ``` - -- UNPKG - - ```html - - ``` - -#### Host the SDK yourself - -Besides using the public CDN, you can also download the SDK and host its files on your own server or a commercial CDN before including it in your application. - -Options to download the SDK: - -- From the website - - Download the JavaScript Package - -- npm - - ```cmd - npm i dynamsoft-javascript-barcode -E - ``` - -- yarn - - ```cmd - yarn add dynamsoft-javascript-barcode -E - ``` - -Depending on how you downloaded the SDK and how you intend to use it, you can typically include it like this: - -```html - -``` - -or - -```html - -``` - -or - -```typescript -import { BarcodeScanner } from 'dynamsoft-javascript-barcode'; -``` - -**NOTE** - -* Some older web application servers do not set `.wasm` mimetype as `application/wasm`. Upgrade your web application servers, or define the mimetype yourselves: - * [Apache](https://developer.mozilla.org/en-US/docs/Learn/Server-side/Apache_Configuration_htaccess#media_types_and_character_encodings) - * [IIS](https://docs.microsoft.com/en-us/iis/configuration/system.webserver/staticcontent/mimemap) - * [Nginx](https://www.nginx.com/resources/wiki/start/topics/examples/full/#mime-types) - -* To work properly, the SDK requires a few engine files, which are relatively large and may take quite a few seconds to download. We recommend that you set a longer cache time for these engine files, to maximize the performance of your web application. - - ```cmd - Cache-Control: max-age=31536000 - ``` - - Reference: [Cache-Control](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control). - -### Configure the SDK - -Before using the SDK, you need to configure a few things. - -#### Specify the license - -The SDK requires a license to work, use the API `license` to specify a license key. - -```javascript -Dynamsoft.DBR.BarcodeScanner.license = "YOUR-LICENSE-KEY"; -``` - -To test the SDK, you can request a 30-day trial license via the Request a Trial License link. - -> If you register a Dynamsoft account and download the SDK from the official website, Dynamsoft will automatically generate a 30-day trial license for you, and put the license key into all the samples attached to the SDK. - -#### Specify the location of the "engine" files - -This is usually only required with frameworks like Angular or React, etc. where dbr.js is compiled into another file. - -The purpose is to tell the SDK where to find the engine files (\*.worker.js, \*.wasm.js and \*.wasm, etc.). The API is called `engineResourcePath`: - -```javascript -//The following code uses the jsDelivr CDN, feel free to change it to your own location of these files -Dynamsoft.DBR.BarcodeScanner.engineResourcePath = "https://cdn.jsdelivr.net/npm/dynamsoft-javascript-barcode@9.6.42/dist/"; -``` - -### Interact with the SDK - -#### Create a `BarcodeScanner` object - -You can use one of two classes ( `BarcodeScanner` and `BarcodeReader` ) to interact with the SDK. `BarcodeReader` is a low-level class that processes images directly. `BarcodeScanner` , on the other hand, inherits from `BarcodeReader` and provides high-level APIs and a built-in GUI to allow continuous barcode scanning on video frames. We'll focus on `BarcodeScanner` in this guide. - -To use the SDK, we first create a `BarcodeScanner` object. - -```javascript -Dynamsoft.DBR.BarcodeScanner.license = "YOUR-LICENSE-KEY"; -let scanner = null; -try { - scanner = await Dynamsoft.DBR.BarcodeScanner.createInstance(); -} catch (ex) { - console.error(ex); -} -``` - -Tip: When creating a `BarcodeScanner` object within a function which may be called more than once, it's best to use a "helper" variable to avoid double creation such as `pScanner` in the following code - -```javascript -Dynamsoft.DBR.BarcodeScanner.license = "YOUR-LICENSE-KEY"; -let pScanner = null; -document.getElementById('btn-scan').addEventListener('click', async () => { - try { - const scanner = await (pScanner = pScanner || Dynamsoft.DBR.BarcodeScanner.createInstance()); - } catch (ex) { - console.error(ex); - } -}); -``` - -#### Customize the `BarcodeScanner` Settings (optional) - -Let's take a look at the following code snippets: - -```javascript -// Sets which camera and what resolution to use -let allCameras = await scanner.getAllCameras(); -await scanner.setCurrentCamera(allCameras[0].deviceId); -await scanner.setResolution(1280, 720); -``` - -```javascript -// Sets up the scanner behavior -let scanSettings = await scanner.getScanSettings(); -// Disregards duplicated results found in a specified time period (in milliseconds). -scanSettings.duplicateForgetTime = 5000; // The default is 3000 -// Sets a scan interval in milliseconds so the SDK may release the CPU from time to time. -// (setting this value larger is a simple way to save battery power and reduce device heating). -scanSettings.intervalTime = 100; // The default is 0. -// Sets captureAndDecodeInParallel to false, which tells the SDK not to acquire the next frame while decoding the first. -// This is another way to save battery power and is recommended on low-end phones. However, it does slow down the decoding speed. -scanSettings.captureAndDecodeInParallel = false; // The default is true. -await scanner.updateScanSettings(scanSettings); -``` - -```javascript -// Uses one of the built-in RuntimeSetting templates: "single" (decode a single barcode, the default mode), "speed", "balance", "coverage", "dense" and "distance" -await scanner.updateRuntimeSettings("speed"); - -// Makes changes to the template. The code below demonstrates how to specify enabled symbologies -let runtimeSettings = await scanner.getRuntimeSettings(); -runtimeSettings.barcodeFormatIds = Dynamsoft.DBR.EnumBarcodeFormat.BF_ONED | Dynamsoft.DBR.EnumBarcodeFormat.BF_QR_CODE; -await scanner.updateRuntimeSettings(runtimeSettings); -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/yfkcajxz/) - -As you can see from the above code snippets, there are three types of configurations: - -- Customize the data source: This configuration includes which camera to use, the preferred resolution, etc. Learn more here. - -- `get/updateScanSettings`: Configures the behavior of the scanner which includes `duplicateForgetTime` and `intervalTime`, etc. - -- `get/updateRuntimeSettings`: Configures the decode engine with either a built-in template or a comprehensive `RuntimeSettings` object. For example, the following uses the built-in "speed" settings with updated `localizationModes`. - - ```javascript - await barcodeScanner.updateRuntimeSettings("speed"); - //await barcodeScanner.updateRuntimeSettings("balance"); //alternative - //await barcodeScanner.updateRuntimeSettings("coverage"); //alternative - let settings = await barcodeScanner.getRuntimeSettings(); - settings.localizationModes = [ - Dynamsoft.DBR.EnumLocalizationMode.LM_CONNECTED_BLOCKS, - Dynamsoft.DBR.EnumLocalizationMode.LM_SCAN_DIRECTLY, - Dynamsoft.DBR.EnumLocalizationMode.LM_LINES, 0, 0, 0, 0, 0 - ]; - await barcodeScanner.updateRuntimeSettings(settings); - ``` - - Try in [JSFiddle](https://jsfiddle.net/DynamsoftTeam/f24h8c1m/). - - See also [settings samples](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/parameter-settings.html?ver=9.6.42&utm_source=guide). - -> Find the full list of the runtime settings here. - -### Customize the UI (optional) - -The built-in UI of the `BarcodeScanner` object is defined in the file `dist/dbr.ui.html` . There are a few ways to customize it: - -#### Modify the file `dist/dbr.ui.html` directly - - This option is only possible when you [Host the SDK yourself](#host-the-sdk-yourself) instead of using a public CDN. - -#### Copy the file `dist/dbr.ui.html` to your application, modify it and use the the API `defaultUIElementURL` to set it as the default UI - - ```javascript - // This line only takes effect before the method `createInstance()` is called. - Dynamsoft.DBR.BarcodeScanner.defaultUIElementURL = "THE-URL-TO-THE-FILE"; - ``` - -#### Append the default UI element to your page, customize it before showing it - - ```html -
- ``` - - ```javascript - document.getElementById('div-ui-container').appendChild(scanner.getUIElement()); - document.getElementsByClassName('dce-btn-close')[0].hidden = true; // Hide the close button - ``` - -#### Build the UI element from scratch and connect it to the SDK with the API `setUIElement(HTMLElement)` - -1. **Embed the video** - - ```html -
-
-
- - ``` - - > 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` . - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/2jzeq1r6/) - -2. **[Optional] Add the camera list and resolution list** - - If the class names of the created select elements match the default class names, i.e. `dce-sel-camera` and `dce-sel-resolution` respectively, the SDK will automatically populate the lists and handle the camera/resolution switching. - - ```html -
-
-
-
- ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/nbj75vxu/) - - ```html -
- - -
-
-
- ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/25v08paf/) - - > By default, only 3 hard-coded resolutions (1920 x 1080, 1280 x 720,640 x 480) are populated as options. You can show a customized set of options by hardcoding them. - - ```html - - ``` - - [Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/tnfjks4q/) - - > Generally, you need to provide a resolution that the camera supports. However, in case a camera does not support the specified resolution, it usually uses the closest supported resolution. As a result, the selected resolution may not be the actual resolution. In this case, add an option with the class name `dce-opt-gotResolution` (as shown above) and the SDK will automatically use it to show the **actual resolution**. - - See the section of the Explore Features guide on [UI customization]({{site.features}}customize-the-ui.html?lang=js) to learn more. - -## API Documentation - -You can check out the detailed documentation about the APIs of the SDK at -[https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/?ver=9.6.42](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/?ver=9.6.42). - -## System Requirements - -DBR requires the following features to work: - -- Secure context (HTTPS deployment) - - When deploying your application / website for production, make sure to serve it via a secure HTTPS connection. This is required for two reasons - - - Access to the camera video stream is only granted in a security context. Most browsers impose this restriction. - > Some browsers like Chrome may grant the access for `http://127.0.0.1` and `http://localhost` or even for pages opened directly from the local disk (`file:///...`). This can be helpful for temporary development and test. - - - Dynamsoft License requires a secure context to work. - -- `WebAssembly`, `Blob`, `URL`/`createObjectURL`, `Web Workers` - - The above four features are required for the SDK to work. - -- `MediaDevices`/`getUserMedia` - - This API is only required for in-browser video streaming. If a browser does not support this API, the [Single Frame Mode](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/BarcodeScanner.html?ver=9.6.42&utm_source=guide#singleframemode) will be used automatically. If the API exists but doesn't work correctly, the Single Frame Mode can be used as an alternative way to access the camera. - -- `getSettings` - - This API inspects the video input which is a `MediaStreamTrack` object about its constrainable properties. - -The following table is a list of supported browsers based on the above requirements: - - Browser Name | Version - :-: | :-: - Chrome | v59+1 - Firefox | v52+ (v55+ on Android/iOS1) - Edge2 | v16+ - Safari3 | v11+ - - 1 iOS 14.3+ is required for camera video streaming in Chrome and Firefox or Apps using webviews. - - 2 On Edge, due to strict Same-origin policy, you must host the SDK files on the same domain as your web page. - - 3 Safari v11.x already has the required features, but it has many other issues, so we recommend v12+. - -Apart from the browsers, the operating systems may impose some limitations of their own that could restrict the use of the SDK. Browser compatibility ultimately depends on whether the browser on that particular operating system supports the features listed above. - -## How to Upgrade - -If you want to upgrade the SDK from an old version to a newer one, please see [how to upgrade](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/upgrade-guide/?ver=9.6.42&utm_source=guide). - -## Release Notes - -Learn about what are included in each release at [https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/release-notes/?ver=latest](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/release-notes/?ver=latest). - -## Next Steps - -Now that you have got the SDK integrated, you can choose to move forward in the following directions - -1. Check out the [Official Samples and Demo](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/index.html?ver=latest) -2. Learn how to make use of the [SDK features](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/user-guide/explore-features/index.html?ver=latest) -3. See how the SDK works in [Popular Use Cases](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/user-guide/use-cases/index.html?ver=latest) diff --git a/programming-old/javascript/user-guide/optimize-performance.md b/programming-old/javascript/user-guide/optimize-performance.md deleted file mode 100644 index e4989d34..00000000 --- a/programming-old/javascript/user-guide/optimize-performance.md +++ /dev/null @@ -1,137 +0,0 @@ ---- -layout: default-layout -title: Advanced Customizations - Dynamsoft Barcode Reader JavaScript Edition -description: This page shows how to optimize the performance of Dynamsoft Barcode Reader JavaScript SDK. -keywords: user guide, advanced customizations, debug, area, region, javascript, js -needAutoGenerateSidebar: true ---- - -# Advanced Usage - -- [Advanced Usage](#advanced-usage) - - [Read a specific area/region](#read-a-specific-arearegion) - - [Account for newline characters in the barcode result](#account-for-newline-characters-in-the-barcode-result) - - [Show internal logs](#show-internal-logs) - - [Set mode arguments](#set-mode-arguments) - - [Display images in different stages of the reading process](#display-images-in-different-stages-of-the-reading-process) - -## Read a specific area/region - -To speed up the scanning process, you can choose to scan only a specific area/region. - -```javascript -let settings = await scanner.getRuntimeSettings(); -/* - * The following code shrinks the decoding region by 25% on all sides - */ -settings.region.regionMeasuredByPercentage = 1; -settings.region.regionLeft = 25; -settings.region.regionTop = 25; -settings.region.regionRight = 75; -settings.region.regionBottom = 75; -await scanner.updateRuntimeSettings(settings); -``` - -[Try in JSFiddle](https://jsfiddle.net/DynamsoftTeam/taykq592/) - -## Account for newline characters in the barcode result - -When it comes to HTML, newline characters ( `\n` ) are not interpreted as they normally would. Therefore, if a barcode result contains a newline character, and you display the result in an modal dialogue box or some other text elements, then the newline character will probably be ignored. - -There are two ways in which you can resolve this: - -1. Wrap the element used to display the result in a `
` element.
-2. Manually replace each `\n` character in the result with `
` - -## Show internal logs - -Include the following in your code to print internal logs in the console. - -```javascript -Dynamsoft.DBR.BarcodeReader._onLog = console.log; -``` - -## Set mode arguments - -To precisely control a mode, you can adjust its specific parameters. - -```javascript -let settings = await scanner.getRuntimeSettings(); - -/* - * The following code sets the sensitivity of the TextureDetectionModes to 9 - */ - -settings.furtherModes.textureDetectionModes = [ - Dynamsoft.DBR.EnumTextureDetectionMode.TDM_GENERAL_WIDTH_CONCENTRATION, 0, 0, 0, 0, 0, 0, 0 -]; - -await scanner.updateRuntimeSettings(settings); -// The 2nd parameter 0 specifies the 0th mode of TextureDetectionModes, -// which is "Dynamsoft.DBR.EnumTextureDetectionMode.TDM_GENERAL_WIDTH_CONCENTRATION" in this case. -await scanner.setModeArgument("TextureDetectionModes", 0, "Sensitivity", "9"); -``` - -## Display images in different stages of the reading process - -The original canvases are saved when setting `ifSaveOriginalImageInACanvas` to `true`. The method `getOriginalImageInACanvas()` returns a canvas which holds the image to be passed to the barcode reader engine for decoding. - -The intermediate result canvases are created when `intermediateResultTypes` is set to a value other than `IRT_NO_RESULT` . Then these intermediate result canvases can be returned with the method `getIntermediateCanvas()` to be used for showing and debugging the barcode reading process. - -> *NOTE* -> -> For efficiency, the library may utilize WebGL (Web Graphics Library) for preprocessing an image before passing it to the barcode reader engine. If WebGL is used, the image captured from the camera will not be rendered on the canvas, instead, it gets processed by WebGL first and then is passed to the barcode reader engine directly. In this case, there won't be an original canvas. -> -> Therefore, if `ifSaveOriginalImageInACanvas` is set to `true` for a `BarcodeScanenr` instance, the WebGL feature will be disabled for that instance. -> -> You can manually disable the WebGL feature by setting `_bUseWebgl` as `false`. If WebGL is disabled, when you try to get the intermediate result canvas (with `getIntermediateCanvas()`) specified by `EnumIntermediateResultType.IRT_ORIGINAL_IMAGE` , the canvas will be exactly the same image as you would get with `getOriginalImageInACanvas()` . - -The following shows how to display these images on the page - -```html -
-
-``` - -```javascript -// original canvas -(async () => { - let scanner = await Dynamsoft.DBR.BarcodeScanner.createInstance(); - document.getElementById('scannerV').appendChild(scanner.getUIElement()); - scanner.ifSaveOriginalImageInACanvas = true; - scanner.onUniqueRead = async (txt, result) => { - try { - let cvs = scanner.getOriginalImageInACanvas(); - document.getElementById('cvses').appendChild(cvs); - scanner.destroyContext(); - } catch (ex) { - console.error(ex); - } - }; - await scanner.show(); -})(); -``` - -```javascript -// intermediate result canvas -(async () => { - let scanner = await Dynamsoft.DBR.BarcodeScanner.createInstance(); - // scanner._bUseWebgl = false; - document.getElementById('scannerV').appendChild(scanner.getUIElement()); - let rs = await scanner.getRuntimeSettings(); - rs.intermediateResultTypes = Dynamsoft.DBR.EnumIntermediateResultType.IRT_ORIGINAL_IMAGE; - await scanner.updateRuntimeSettings(rs); - scanner.onUniqueRead = async (txt, result) => { - try { - let cvss = await scanner.getIntermediateCanvas(); - for (let cvs of cvss) { - document.getElementById('cvses').appendChild(cvs); - } - scanner.destroyContext(); - } catch (ex) { - console.error(ex); - } - }; - await scanner.show(); -})(); -``` \ No newline at end of file diff --git a/programming-old/javascript/user-guide/upgrade-v7.6.0.md b/programming-old/javascript/user-guide/upgrade-v7.6.0.md deleted file mode 100644 index db4840e8..00000000 --- a/programming-old/javascript/user-guide/upgrade-v7.6.0.md +++ /dev/null @@ -1,29 +0,0 @@ ---- -layout: default-layout -title: v7.6.0 User guide: How to Upgrade - Dynamsoft Barcode Reader JavaScript Edition -description: This page shows how to upgrade Dynamsoft Barcode Reader JavaScript SDK from v7.x to v9.x. -keywords: user guide, upgrade, javascript, js -needAutoGenerateSidebar: true -permalink: /programming/javascript/user-guide/upgrade-v7.6.0.html ---- - -# How to Upgrade - -## From version 7.2.2-v2 and above - -If you are using a **CDN**, simply update the version number denoted after **@** in the URL. - - ```html - - ``` - -If you have deployed the library files on your own server, you'll need to replace the old files with the ones in the latest version. Download the latest version [here](https://www.dynamsoft.com/Downloads/Dynamic-Barcode-Reader-Download.aspx). - -## From version 7.2.2-v2 or below - -Some major changes were made in version 7.2.2-v2 and will require existing code updates in your application. - -Follow the detailed guide in [this post](https://www.dynamsoft.com/blog/announcement/dynamsoft-barcode-reader-sdk-for-javascript-upgrade-from-v7-1-3-to-v7-2-2/) for upgrade steps. - -If you need further assistance with the upgrade, please feel free to [contact us](https://www.dynamsoft.com/Company/Contact.aspx). - diff --git a/programming-old/javascript/user-guide/upgrade-v9.6.31.md b/programming-old/javascript/user-guide/upgrade-v9.6.31.md deleted file mode 100644 index b1260dff..00000000 --- a/programming-old/javascript/user-guide/upgrade-v9.6.31.md +++ /dev/null @@ -1,131 +0,0 @@ ---- -layout: default-layout -title: How to Upgrade - Dynamsoft Barcode Reader JavaScript Edition -description: This page shows how to upgrade Dynamsoft Barcode Reader JavaScript SDK up till version 8.2.5. -keywords: user guide, upgrade, javascript, js -needAutoGenerateSidebar: true -permalink: /programming/javascript/user-guide/upgrade-v9.6.31.html ---- - -# How to Upgrade - -## From v8.x to v8.2.5 - -In v8.2.5, we introduced the API `organizationID` as the recommended way to fetch a trackable license. However, all old ways of licensing the library are still supported. - ---- -## From v8.x to v8.1.2 - -### `TextResult` exception - -In v8.1, we added exceptions to the `TextResult` class. An exception message and code is returned with each result if no valid license (trial or full) is present. - -The following is an example of what may be returned: - -`[Attention(exceptionCode:-20000)] http:/*d*n*m*soft.q*.com*r/U4***U*EaRA****W9*ZB` - -More details on the exception can be found within each result. For example: - -``` -result.exception = { - code: "-20000", - message: "No license specified. Visit https://www.dynamsoft.com/customer/license/trialLicense?utm_source=guide&product=dbr&package=js to acquire a license or email support@dynamsoft.com." -} -``` - ---- -## From v7.x to v8.x - -### Change your license - -In v8.0, we introduced a new license tracking mechanism, [License 2.0](https://www.dynamsoft.com/license-tracking/docs/about/index.html). If you have a v7.x license and wish to upgrade to v8.x, you must [contact us](https://www.dynamsoft.com/Company/Contact.aspx) to acquire a new license. - -### Update version and code - -If you are using a **CDN**, simply update the version number denoted after **@** in the URL. - -```html - -``` - -If you have deployed the library files to your server, you'll need to replace the old files with the ones in the latest version. Download the latest version [here](https://www.dynamsoft.com/Downloads/Dynamic-Barcode-Reader-Download.aspx). - -Next, replace the value ("PRODUCT-KEYS") of `data-productKeys` with the handshake code or organization ID you receive based on License 2.0 (as mentioned in the section [Change your license](#change-your-license) above). - -### API changes - -#### :exclamation: *Namespace change* - -Use the new namespace `Dynamsoft.DBR` in place of just `Dynamsoft`. The following shows the equivalent changes for `BarcodeScanner` and `BarcodeReader`: - -```js -Dynamsoft.BarcodeScanner -> Dynamsoft.DBR.BarcodeScanner -Dynamsoft.BarcodeReader -> Dynamsoft.DBR.BarcodeReader -``` - -If you are using the library as an ES/CMD module, you don't need to change your code. Otherwise, you can either make a global change from `Dynamsoft` to `Dynamsoft.DBR` or use the following line to quickly make the namespace change. - -```js -Dynamsoft = Dynamsoft.DBR; //This line should be called before you call any other methods/properties of the library. -``` - -#### Deprecating `deblurLevel` - -`deblurLevel` has been deprecated in v8.0 and replaced with `deblurModes`. Although `deblurLevel` will continue to work in v8.0, we recommend updating your code to use `deblurModes` as soon as possible to avoid any breaking changes in the future. - -Check out the code below on how to switch from `deblurLevel` to `deblurModes`. - -```js -let settings = await barcodeScanner.getRuntimeSettings(); -//settings.deblurLevel = 9; -settings.deblurModes = ["DM_DIRECT_BINARIZATION", - "DM_THRESHOLD_BINARIZATION", - "DM_GRAY_EQUALIZATION", - "DM_SMOOTHING", - "DM_MORPHING", - "DM_DEEP_ANALYSIS", - "DM_SHARPENING", - "DM_SKIP"] -await barcodeScanner.updateRuntimeSettings(settings); -``` - -#### Default runtime setting has changed from `speed` to `single` for `BarcodeScanner` - -The `single` runtime setting was introduced in v7.5 as an experimental feature for `BarcodeScanner`. In v8.0, `single` is made the default setting. - -Before v8.0, the default setting was `speed`. - -*NOTE* - -`BarcodeReader` still uses `coverage` as the default setting. - -#### Removed some deprecated APIs from `textResult` - -* `BarcodeText` is removed, use `barcodeText` instead -* `BarcodeFormat` is removed, use `barcodeFormat` instead -* `BarcodeFormatString` is removed, use `barcodeFormatString` instead -* `LocalizationResult` is removed, use `localizationResult` instead -* `ResultPoints` in `localizationResult` is removed, use `x1,x2,x3,x4,y1,y2,y3,y4` instead -* `accompanyingTextBytes` is removed, if you wish to use the feature or something similar, please [contact us](https://www.dynamsoft.com/Company/Contact.aspx). - ---- -## Upgrade to v7.x - -### From version 7.2.2-v2 and above - -If you are using a **CDN**, simply update the version number denoted after **@** in the URL. - - ```html - - ``` - -If you have deployed the library files on your own server, you'll need to replace the old files with the ones in the latest version. Download the latest version [here](https://www.dynamsoft.com/Downloads/Dynamic-Barcode-Reader-Download.aspx). - -### Prior to version 7.2.2-v2 - -Some major changes were made in version 7.2.2-v2 and will require existing code updates in your application. - -Follow the detailed guide in [this post](https://www.dynamsoft.com/blog/announcement/dynamsoft-barcode-reader-sdk-for-javascript-upgrade-from-v7-1-3-to-v7-2-2/) for upgrade steps. - -If you need further assistance with the upgrade, please feel free to [contact us](https://www.dynamsoft.com/Company/Contact.aspx). - diff --git a/programming-old/javascript/user-guide/use-cases/index.md b/programming-old/javascript/user-guide/use-cases/index.md deleted file mode 100644 index b1f5c69d..00000000 --- a/programming-old/javascript/user-guide/use-cases/index.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -layout: default-layout -title: Use Cases - Dynamsoft Barcode Reader JavaScript Edition User Guide -description: This page explores the use cases of Dynamsoft Barcode Reader JavaScript SDK. -keywords: user guide, use cases, javascript, js -breadcrumbText: Use Cases -noTitleIndex: true -needGenerateH3Content: true -needAutoGenerateSidebar: true -permalink: /programming/javascript/user-guide/use-cases/index.html ---- - -# Use Cases - -* [Scan barcodes as input]({{site.usecases}}scan-barcodes-as-input.html?lang=js) -* [Scan and parse PDF417 on AAMVA documents]({{site.usecases}}scan-and-parse-AAMVA.html?lang=js) -* [Read DPM codes]({{site.usecases}}read-dpm-codes.html?lang=js) -* [Read Postal codes]({{site.usecases}}read-postal-codes.html?lang=js) - - \ No newline at end of file diff --git a/programming/javascript/api-reference/barcode-reader-module-v10.5.3000.md b/programming/javascript/api-reference/barcode-reader-module-v10.5.3000.md deleted file mode 100644 index 799c2da4..00000000 --- a/programming/javascript/api-reference/barcode-reader-module-v10.5.3000.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -layout: default-layout -title: BarcodeReader Module - Dynamsoft Barcode Reader JavaScript Edition API -description: This page introduces the BarcodeReader module in Dynamsoft Barcode Reader JavaScript Edition. -keywords: barcode reader, module, api reference, javascript, js -needAutoGenerateSidebar: true -needGenerateH3Content: true -noTitleIndex: true ---- - -# DynamsoftBarcodeReader Module - -The BarcodeReader module is defined in the namespace `Dynamsoft.DBR`. It includes a class named "BarcodeReaderModule" along with various interfaces and enumerations. - -## BarcodeReaderModule Class - -This class defines common functionality in the `BarcodeReader` module. At present, there is only one API. - -| API Name | Description | -| -------------------------------------------------------------------- | ------------------------------------------------ | -| `static` [getVersion()](./barcode-reader-module-class.md#getversion) | Returns the version of the BarcodeReader module. | - -## Interfaces - -* [AztecDetails](./interfaces/aztec-details.md) -* [BarcodeDetails](./interfaces/barcode-details.md) -* [BarcodeResultItem](./interfaces/barcode-result-item.md) -* [CandidateBarcodeZone](./interfaces/candidate-barcode-zone.md) -* [CandidateBarcodeZonesUnit](./interfaces/candidate-barcode-zones-unit.md) -* [ComplementedBarcodeImageUnit](./interfaces/complemented-barcode-image-unit.md) -* [DataMatrixDetails](./interfaces/datamatrix-details.md) -* [DecodedBarcodeElement](./interfaces/decoded-barcode-element.md) -* [DecodedBarcodesResult](./interfaces/decoded-barcodes-result.md) -* [DecodedBarcodesUnit](./interfaces/decoded-barcodes-unit.md) -* [DeformationResistedBarcode](./interfaces/deformation-resisted-barcode.md) -* [DeformationResistedBarcodeImageUnit](./interfaces/deformation-resisted-barcode-image-unit.md) -* [ExtendedBarcodeResult](./interfaces/extended-barcode-result.md) -* [LocalizedBarcodeElement](./interfaces/localized-barcode-element.md) -* [LocalizedBarcodesUnit](./interfaces/localized-barcodes-unit.md) -* [OneDCodeDetails](./interfaces/oned-code-details.md) -* [PDF417Details](./interfaces/pdf417-details.md) -* [QRCodeDetails](./interfaces/qr-code-details.md) -* [ScaledUpBarcodeImageUnit](./interfaces/scaled-up-barcode-image-unit.md) -* [SimplifiedBarcodeReaderSettings](./interfaces/simplified-barcode-reader-settings.md) - -## Enums - -* [EnumBarcodeFormat]({{ site.dcvb_enums }}barcode-reader/barcode-format.html?lang=js) -* [EnumDeblurMode]({{ site.dcvb_enums }}barcode-reader/deblur-mode.html?lang=js) -* [EnumExtendedBarcodeResultType]({{ site.dcvb_enums }}barcode-reader/extended-barcode-result-type.html?lang=js) -* [EnumLocalizationMode]({{ site.dcvb_enums }}barcode-reader/localization-mode.html?lang=js) -* [EnumQRCodeErrorCorrectionLevel]({{ site.dcvb_enums }}barcode-reader/qr-code-error-correction-level.html?lang=js) diff --git a/programming/javascript/api-reference/barcode-scanner-v10.5.3000.md b/programming/javascript/api-reference/barcode-scanner-v10.5.3000.md deleted file mode 100644 index 324bec36..00000000 --- a/programming/javascript/api-reference/barcode-scanner-v10.5.3000.md +++ /dev/null @@ -1,409 +0,0 @@ ---- -layout: default-layout -title: BarcodeScanner JavaScript Edition - API Reference -keywords: Documentation, BarcodeScanner JavaScript Edition, API, APIs -breadcrumbText: BarcodeScanner API References -description: Dynamsoft BarcodeScanner JavaScript Edition - API Reference -needAutoGenerateSidebar: true -needGenerateH3Content: true -noTitleIndex: true ---- - -# Barcode Scanner JavaScript Edition API Reference - -BarcodeScanner is a configurable barcode scanning module featuring a pre-built UI that supports both live camera and still image decoding. Designed for effortless integration into web applications, it offers a ready-to-use, customizable interface to streamline barcode scanning implementation. - -## Constructor - -### BarcodeScanner - -```ts -new BarcodeScanner(config?: BarcodeScannerConfig) -``` - -**Parameters** - -`config` (optional): Assigns the license and configures the different settings of the `BarcodeScanner`, including the container, supported barcode formats, and more. This config object is of type [*BarcodeScannerConfig*](#barcodescannerconfig). - -**Code Snippet** - -```js -const barcodeScanner = new Dynamsoft.BarcodeScanner({ - license: "YOUR_LICENSE_KEY_HERE", - scannerViewConfig: { - // container: "#camera-view-container", - // showCloseButton: true, - }, - // showUploadImageButton: true, - // scanMode: Dynamsoft.EnumScanMode.SM_MULTI_UNIQUE, - // showResultView: true, -}); -``` - -## Methods - -### launch() - -Launches the scanner and optionally renders the scanning UI based on scanMode and container configuration. - -```ts -launch(): Promise -``` - -**Returns** - -A promise that resolves to a [`BarcodeScanResult`](#barcodescanresult). - -**Code Snippet** - -```js -(async () => { - // Launch the scanner and wait for the result - try { - const result = await barcodeScanner.launch(); - console.log(result); // print the BarcodeScanResult to the console - } catch (error){ - console.error(error); - } -})(); -``` - -### dispose() - -Disposes the scanner instance and cleans up all related resources. - -```ts -dispose(): void -``` - -**Code Snippet** - -```js -barcodeScanner.dispose(); -console.log("Scanner resources released."); -``` - -### decode() - -Decodes a barcode from an image, URL, or canvas element. - -```ts -decode(imageOrFile: Blob | string | DSImageData | HTMLImageElement | HTMLVideoElement | HTMLCanvasElement,templateName?: string): Promise -``` - -**Parameters** - -`imageOrFile`: The input image source. - -`templateName` (optional): The name of the [`CaptureVisionTemplate`]({{ site.dcvb_js_api }}capture-vision-router/preset-templates.html) to be used. - -**Returns** - -A promise that resolves to a `CapturedResult`. - -**Code Snippet** - -```js -const imageUrl = 'https://example.com/image.png'; -const results = barcodeScanner.decode(imageUrl); -//... do something with the results -``` - -## Interfaces - -### BarcodeScannerConfig - -Configuration options for initializing a `BarcodeScanner`. - -```ts -interface BarcodeScannerConfig { - license?: string; - scanMode?: EnumScanMode; - templateFilePath?: string; - utilizedTemplateNames?: UtilizedTemplateNames; - engineResourcePaths?: EngineResourcePaths; - uiPath?: string; - barcodeFormats?: EnumBarcodeFormat | Array; - duplicateForgetTime?: number; - removePoweredByMessage?: boolean; - container?: HTMLElement | string | undefined; - onUniqueBarcodeScanned?: (result: BarcodeResultItem) => void | Promise; - showResultView?: boolean; - showUploadImageButton?: boolean; - scannerViewConfig?: ScannerViewConfig; - resultViewConfig?: ResultViewConfig; -} -``` - -| Property | Type | Default Value | Description | -| ----------------------- | ------------------------------ | --- | --------------------------------------------------------------- | -| `license` | `string` | `N/A` | The license key to activate the barcode scanner. | -| `scanMode`(optional) | [`EnumScanMode`](#enumscanmode) | `SM_SINGLE` | Defines the scan mode of the BarcodeScanner| -| `templateFilePath`(optional) | `string` | `N/A` | Path to a CaptureVisionTemplate file used for barcode reading. | -| `utilizedTemplateNames`(optional) | `UtilizedTemplateNames` | `{"single": "ReadSingleBarcode", "multi_unique": "ReadBarcodes_SpeedFirst", "image": "ReadBarcodes_ReadRateFirst"}` | Defines template names mapped to scanning modes. | -| `engineResourcePaths`(optional) | `EngineResourcePaths` | `N/A` | Paths to engine resources like WASM or workers. See [EngineResourcePaths](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/core/core-module-class.html?product=dbr&lang=javascript#engineresourcepaths) for details. | -| `uiPath` (optional) | `string` | `N/A` | Path to the custom UI (`.xml` template file) for the ScannerView.| -| `barcodeFormats`(optional) | `EnumBarcodeFormat` \| `Array` | `N/A` | [EnumBarcodeFormat](https://www.dynamsoft.com/capture-vision/docs/core/enums/barcode-reader/barcode-format.html?lang=js&product=dbr) or an array of `EnumBarcodeFormat` specifying the formats to recognize. | -| `duplicateForgetTime`(optional) | `number` | `3000` | Time interval in milliseconds before duplicate barcodes can be reported again. | -| `removePoweredByMessage`(optional) | `boolean` | `false` | Whether to remove the "powered by" message. | -| `container`(optional) | `HTMLElement` \| `string` | `N/A` | A container element or selector for rendering the scanner and/or result view. | -| `onUniqueBarcodeScanned` | `void` \| `Promise` | `N/A` | A callback triggered when a unique barcode is scanned (only valid in SM_MULTI_UNIQUE). | -| `showResultView`(optional) | `boolean` | `false` | Whether to display a result view in SM_MULTI_UNIQUE mode. | -| `showUploadImageButton`(optional) | `boolean` | `false` | Determines the visibility of the "uploadImage" button that allows the user to upload an image for decoding. | -| `scannerViewConfig`(optional) | `ScannerViewConfig` | see [ScannerViewConfig](#scannerviewconfig) | Configuration for the scanner view. | -| `resultViewConfig`(optional) | `ResultViewConfig` | see [ResultViewConfig](#resultviewconfig) | Configuration for the result view (only valid in SM_MULTI_UNIQUE). | - -**Code Snippet** - -```html - -
- - -``` - -### ScannerViewConfig - -The ScannerViewConfig is used to configure the UI elements of the **BarcodeScannerView**. If the ScannerViewConfig is not assigned, then the library will use the default BarcodeScannerView. - -```ts -interface ScannerViewConfig { - container?: HTMLElement | string | undefined; - showCloseButton?: boolean; -} -``` - -| Property | Type | Default Value | Description | -| ----------------------- | ------------------------------ | --- | --------------------------------------------------------------- | -| `container` (optional) | `HTMLElement` \| `string` \| `undefined` | `N/A` | A dedicated container for the ScannerView (video stream). | -| `showCloseButton` (optional) | `boolean` | `false` | Determines the visibility of the "closeButton" button that allows the user to close the ScannerView. | - -**Code Snippet** - -```js -const barcodeScannerViewConfig = { - showCloseButton: true // display the close button that shows up at the top right of the view -}; - -const barcodeScannerConfig = { - license: "YOUR_LICENSE_KEY_HERE", - scannerViewConfig: barcodeScannerViewConfig -}; -``` - -### ResultViewConfig - -The ResultViewConfig is used to configure the UI elements of the **BarcodeResultView**. If the ResultViewConfig is not assigned, then the library will use the default BarcodeResultView. - -```ts -interface ResultViewConfig { - container?: HTMLElement | string | undefined; - toolbarButtonsConfig?: BarcodeResultViewToolbarButtonsConfig; -} -``` - -| Property | Type | Default Value | Description | -| ----------------------- | ------------------------------ | --- | --------------------------------------------------------------- | -| `container` (optional) | `HTMLElement` \| `string` \| `undefined` | `N/A` | A dedicated container for the ResultView. | -| `toolbarButtonsConfig` (optional) | `BarcodeResultViewToolbarButtonsConfig` | see [BarcodeResultViewToolbarButtonsConfig](#barcoderesultviewtoolbarbuttonsconfig) | Configures the main bottom toolbar of the ResultView.| - -**Code Snippet** - -```js -const barcodeResultViewConfig = { - toolbarButtonsConfig: { - clear: { - label: "Clear-all", // Changes the text label of the clear button to "Clear-all"; string is "Clear" by default - isHidden: true // Hides the clear button; false by default - }, - done: { - label: "Return Home", // Changes the text label of the done button to "Return Home"; string is "Done" by default - isHidden: false // Hides the done button; false by default - } - }, -} - -const barcodeScannerConfig = { - license: "YOUR_LICENSE_KEY_HERE", - resultViewConfig: barcodeResultViewConfig -}; -``` - -### BarcodeResultViewToolbarButtonsConfig - -The BarcodeResultViewToolbarButtonsConfig is used to configure the buttons of the toolbar in the BarcodeResultView. - -```ts -interface BarcodeResultViewToolbarButtonsConfig { - clear?: ToolbarButtonConfig; - done?: ToolbarButtonConfig; -} -``` - -| Property | Type | Description | -| ----------------------- | ------------------------------ | --------------------------------------------------------------- | -| `clear` (optional) | [`ToolbarButtonConfig`](#toolbarbuttonconfig) | Configuration for the clear button of the toolbar. | -| `done` (optional) | [`ToolbarButtonConfig`](#toolbarbuttonconfig) | Configuration for the done button of the toolbar. | - -**Code Snippet** - -```js -// Default value as shown below -const barcodeScannerButtonConfig = { - clear: { - label: "Clear", - isHidden: false - }, - done: { - label: "Done", - isHidden: false - } -}; - -const barcodeResultViewConfig = { - toolbarButtonsConfig: barcodeScannerButtonConfig -}; -``` - -### ToolbarButtonConfig - -The interface used to configure the properties of the toolbar button. - -```ts -interface ToolbarButtonConfig { - label: string; - className?: string; - isHidden?: boolean; -} -``` - -| Property | Type | Description | -| ----------------------- | ------------------------------ | --------------------------------------------------------------- | -| `label` | `string` | The text label of the button. | -| `className` | `string` | Assigns a custom class to the button (usually to apply custom styling). | -| `isHidden` | `boolean` | Hides/Shows the button in the toolbar. | - -### BarcodeScanResult - -The BarcodeScanResult is the most basic interface that is used to represent the full barcode scan result object. It comes with a result status, the original and cropped image result, and the detailed info of the decoded barcode(s). - -```ts -interface BarcodeScanResult { - status: ResultStatus; - barcodeResults?: BarcodeResultItem[]; - originalImageResult?: DSImageData; - barcodeImage?: DSImageData; -} -``` - -| Property | Type | Description | -| ----------------------- | ------------------------------ | --------------------------------------------------------------- | -| `status` (optional) | [`ResultStatus`](#resultstatus) | The status of the barcode scanning, which can be success, cancelled, or failed (indicating that something has gone wrong during the scanning process). | -| `originalImageResult` (optional) | [`DSImageData`]({{ site.dcvb_js_api }}core/basic-structures/ds-image-data.html) | A `DSImageData` object that represents the original image of the successfully decoded barcode. | -| `barcodeResults` (optional) | [`Array`]({{ site.js_api }}interfaces/barcode-result-item.html) | An array of BarcodeResultItem Represents the decoded barcode(s). | - -**Code Snippet** - -```js -(async () => { - // Launch the scanner and wait for the result - const result = await barcodeScanner.launch(); - console.log(result.status.message); // prints the result status message to the console - console.log(result.status.code); // prints the result status code to the console - console.log(result.barcodeResults); // prints an array containing all the decoded barcode results to the console. Note that in SM_SINGLE mode, the length of this array is 1. -})(); -``` - -### UtilizedTemplateNames - -An object that defines the names of templates utilized by the BarcodeScanner for different scanning modes. - -```ts -interface UtilizedTemplateNames { - single: string; - multi_unique: string; - image: string; -} -``` - -| Property | Type | Description | -| ----------------------- | ------------------------------ | --------------------------------------------------------------- | -| `single` | `string` | Template name used for single barcode scanning mode. | -| `multi_unique` | `string` | Template name used for scanning multiple unique barcodes. | -| `image` | `string` | Template name used when barcode scanning is based on a provided image input. | - -**Code Snippet** - -```js -const barcodeScannerConfig = { - //.. - utilizedTemplateNames:{ - single: `ReadSingleBarcode`, - multi_unique: `ReadBarcodes_SpeedFirst`, - image: `ReadBarcodes_ReadRateFirst`, - } - //.. -} -``` - -### ResultStatus - -ResultStatus is used to represent the status of the barcode scanning result. This status can be **success**, **cancelled** if the user closes the scanner during scanning, or **failed** if something went wrong during the scanning process. The *code* of the result status is a [`EnumResultStatus`](#enumresultstatus). - -```ts -type ResultStatus = { - code: EnumResultStatus; - message: string; -} -``` - -## Enums - -### EnumScanMode - -```ts -enum EnumScanMode { - SM_SINGLE = 0, - SM_MULTI_UNIQUE = 1 -} -``` - -### EnumResultStatus - -```ts -enum EnumResultStatus { - RS_SUCCESS = 0, - RS_CANCELLED = 1, - RS_FAILED = 2 -} -``` \ No newline at end of file diff --git a/programming/javascript/api-reference/index-v10.5.3000.md b/programming/javascript/api-reference/index-v10.5.3000.md deleted file mode 100644 index 43bfa0c7..00000000 --- a/programming/javascript/api-reference/index-v10.5.3000.md +++ /dev/null @@ -1,180 +0,0 @@ ---- -layout: default-layout -title: Dynamsoft Barcode Reader JavaScript Edition v10.x API Reference - Main Page -description: This is the main page of Dynamsoft Barcode Reader for JavaScript SDK API Reference. -keywords: BarcodeReader, api reference, javascript, js -needAutoGenerateSidebar: true -needGenerateH3Content: true -breadcrumbText: API Reference -noTitleIndex: true - ---- - -# Dynamsoft Barcode Reader JavaScript Edition API Reference Index - -## [DynamsoftCaptureVisionRouter]({{ site.dcvb_js_api }}capture-vision-router/capture-vision-router-module.html) - -### Classes - -* [CaptureVisionRouter]({{ site.dcvb_js_api }}capture-vision-router/capture-vision-router-module.html) -* [CaptureVisionRouterModule]({{ site.dcvb_js_api }}capture-vision-router/capture-vision-router-module-class.html) -* [CapturedResultReceiver]({{ site.dcvb_js_api }}capture-vision-router/captured-result-receiver.html) -* [IntermediateResultManager]({{ site.dcvb_js_api }}capture-vision-router/intermediate-result-manager.html) -* [IntermediateResultReceiver]({{ site.dcvb_js_api }}capture-vision-router/intermediate-result-receiver.html) -* [BufferedItemsManager]({{ site.dcvb_js_api }}capture-vision-router/buffered-items-manager.html) - -### Interfaces - -* [CapturedResult]({{ site.dcvb_js_api }}capture-vision-router/interfaces/captured-result.html) -* [SimplifiedCaptureVisionSettings]({{ site.dcvb_js_api }}capture-vision-router/interfaces/simplified-capture-vision-settings.html) - -### Enums - -* [EnumImageSourceState]({{ site.dcvb_enums }}core/image-source-state.html?lang=js) - -## [DynamsoftBarcodeReader](./barcode-reader-module.html) - -### Classes - -* [BarcodeReaderModule](./barcode-reader-module-class.html) - -### Interfaces - -* [AztecDetails](./interfaces/aztec-details.html) -* [BarcodeDetails](./interfaces/barcode-details.html) -* [BarcodeResultItem](./interfaces/barcode-result-item.html) -* [CandidateBarcodeZone](./interfaces/candidate-barcode-zone.html) -* [CandidateBarcodeZonesUnit](./interfaces/candidate-barcode-zones-unit.html) -* [ComplementedBarcodeImageUnit](./interfaces/complemented-barcode-image-unit.html) -* [DataMatrixDetails](./interfaces/datamatrix-details.html) -* [DecodedBarcodeElement](./interfaces/decoded-barcode-element.html) -* [DecodedBarcodesResult](./interfaces/decoded-barcodes-result.html) -* [DecodedBarcodesUnit](./interfaces/decoded-barcodes-unit.html) -* [DeformationResistedBarcode](./interfaces/deformation-resisted-barcode.html) -* [DeformationResistedBarcodeImageUnit](./interfaces/deformation-resisted-barcode-image-unit.html) -* [ExtendedBarcodeResult](./interfaces/extended-barcode-result.html) -* [LocalizedBarcodeElement](./interfaces/localized-barcode-element.html) -* [LocalizedBarcodesUnit](./interfaces/localized-barcodes-unit.html) -* [OneDCodeDetails](./interfaces/oned-code-details.html) -* [PDF417Details](./interfaces/pdf417-details.html) -* [QRCodeDetails](./interfaces/qr-code-details.html) -* [ScaledUpBarcodeImageUnit](./interfaces/scaled-up-barcode-image-unit.html) -* [SimplifiedBarcodeReaderSettings](./interfaces/simplified-barcode-reader-settings.html) - -### Enums - -* [EnumBarcodeFormat]({{ site.dcvb_enums }}barcode-reader/barcode-format.html?lang=js) -* [EnumDeblurMode]({{ site.dcvb_enums }}barcode-reader/deblur-mode.html?lang=js) -* [EnumExtendedBarcodeResultType]({{ site.dcvb_enums }}barcode-reader/extended-barcode-result-type.html?lang=js) -* [EnumLocalizationMode]({{ site.dcvb_enums }}barcode-reader/localization-mode.html?lang=js) -* [EnumQRCodeErrorCorrectionLevel]({{ site.dcvb_enums }}barcode-reader/qr-code-error-correction-level.html?lang=js) - -## [DynamsoftCameraEnhancer]({{ site.dce_js_api }}index.html) - -### Classes - -* [CameraEnhancer]({{ site.dce_js_api }}index.html) -* [CameraView]({{ site.dce_js_api }}cameraview.html) -* [ImageEditorView]({{ site.dce_js_api }}imageeditorview.html) -* [CameraEnhancerModule]({{ site.dce_js_api }}cameraenhancermodule.html) -* [DrawingItem]({{ site.dce_js_api }}drawingitem.html) -* [DrawingLayer]({{ site.dce_js_api }}drawinglayer.html) -* [DrawingStyleManager]({{ site.dce_js_api }}drawinglayer.html) -* [Feedback]({{ site.dce_js_api }}feedback.html) - -### Interfaces - -* [CameraTestResponse]({{ site.dce_js_api }}interface/cameratestresponse.html) -* [DCEFrame]({{ site.dce_js_api }}interface/dceframe.html) -* [DrawingItemEvent]({{ site.dce_js_api }}interface/drawingitemevent.html) -* [DrawingStyle]({{ site.dce_js_api }}interface/drawingstyle.html) -* [Note]({{ site.dce_js_api }}interface/note.html) -* [PlayCallbackInfo]({{ site.dce_js_api }}interface/playcallbackinfo.html) -* [Resolution]({{ site.dce_js_api }}interface/resolution.html) -* [TipConfig]({{ site.dce_js_api }}interface/tipconfig.html) -* [VideoDevice]({{ site.dce_js_api }}interface/videodevice.html) -* [VideoFrameTag]({{ site.dce_js_api }}interface/videoframetag.html) - -### Enums - -* [EnumDrawingItemMediaType]({{ site.dce_js_api }}enum/enumdrawingitemmediatype.html) -* [EnumDrawingItemState]({{ site.dce_js_api }}enum/enumdrawingitemstate.html) -* [EnumEnhancedFeatures]({{ site.dce_js_api }}enum/enumenhancedfeatures.html) - -## [DynamsoftCore]({{ site.dcvb_js_api }}core/core-module.html) - -### Classes - -* [CoreModule]({{ site.dcvb_js_api }}core/core-module-class.html) -* [ImageSourceAdapter]({{ site.dcvb_js_api }}core/image-source-adapter.html) - -### Interfaces - -* [Arc]({{ site.dcvb_js_api }}core/basic-structures/arc.html) -* [Contour]({{ site.dcvb_js_api }}core/basic-structures/contour.html) -* [Corner]({{ site.dcvb_js_api }}core/basic-structures/corner.html) -* [DSRect]({{ site.dcvb_js_api }}core/basic-structures/ds-rect.html) -* [Edge]({{ site.dcvb_js_api }}core/basic-structures/edge.html) -* [LineSegment]({{ site.dcvb_js_api }}core/basic-structures/line-segment.html) -* [Point]({{ site.dcvb_js_api }}core/basic-structures/point.html) -* [Polygon]({{ site.dcvb_js_api }}core/basic-structures/polygon.html) -* [Quadrilateral]({{ site.dcvb_js_api }}core/basic-structures/quadrilateral.html) -* [Rect]({{ site.dcvb_js_api }}core/basic-structures/rect.html) -* [CapturedResultItem]({{ site.dcvb_js_api }}core/basic-structures/captured-result-item.html) -* [DSFile]({{ site.dcvb_js_api }}core/basic-structures/ds-file.html) -* [DSImageData]({{ site.dcvb_js_api }}core/basic-structures/ds-image-data.html) -* [ImageSourceErrorListener]({{ site.dcvb_js_api }}core/basic-structures/image-source-error-listener.html) -* [ImageTag]({{ site.dcvb_js_api }}core/basic-structures/image-tag.html) -* [OriginalImageResultItem]({{ site.dcvb_js_api }}core/basic-structures/original-image-result-item.html) -* [TextZone]({{ site.dcvb_js_api }}core/intermediate-results/text-zone.html) -* [Warning]({{ site.dcvb_js_api }}core/basic-structures/warning.html) -* [BinaryImageUnit]({{ site.dcvb_js_api }}core/intermediate-results/binary-image-unit.html) -* [ColourImageUnit]({{ site.dcvb_js_api }}core/intermediate-results/colour-image-unit.html) -* [ContoursUnit]({{ site.dcvb_js_api }}core/intermediate-results/contours-unit.html) -* [EnhancedGrayscaleImageUnit]({{ site.dcvb_js_api }}core/intermediate-results/enhanced-grayscale-image-unit.html) -* [GrayscaleImageUnit]({{ site.dcvb_js_api }}core/intermediate-results/grayscale-image-unit.html) -* [IntermediateResult]({{ site.dcvb_js_api }}core/intermediate-results/intermediate-result.html) -* [IntermediateResultExtraInfo]({{ site.dcvb_js_api }}core/intermediate-results/intermediate-result-extra-info.html) -* [IntermediateResultUnit]({{ site.dcvb_js_api }}core/intermediate-results/intermediate-result-unit.html) -* [ObservationParameters]({{ site.dcvb_js_api }}core/intermediate-results/observation-parameters.html) -* [LineSegmentsUnit]({{ site.dcvb_js_api }}core/intermediate-results/line-segments-unit.html) -* [PredetectedRegionElement]({{ site.dcvb_js_api }}core/intermediate-results/predetected-region-element.html) -* [PredetectedRegionsUnit]({{ site.dcvb_js_api }}core/intermediate-results/predetected-regions-unit.html) -* [RegionObjectElement]({{ site.dcvb_js_api }}core/intermediate-results/region-object-element.html) -* [ScaledDownColourImageUnit]({{ site.dcvb_js_api }}core/intermediate-results/scaled-down-colour-image-unit.html) -* [TextRemovedBinaryImageUnit]({{ site.dcvb_js_api }}core/intermediate-results/text-removed-binary-image-unit.html) -* [TextureDetectionResultUnit]({{ site.dcvb_js_api }}core/intermediate-results/texture-detection-result-unit.html) -* [TextureRemovedBinaryImageUnit]({{ site.dcvb_js_api }}core/intermediate-results/texture-removed-binary-image-unit.html) -* [TextureRemovedGrayscaleImageUnit]({{ site.dcvb_js_api }}core/intermediate-results/texture-removed-grayscale-image-unit.html) -* [TextZonesUnit]({{ site.dcvb_js_api }}core/intermediate-results/text-zones-unit.html) -* [TransformedGrayscaleImageUnit]({{ site.dcvb_js_api }}core/intermediate-results/transformed-grayscale-image-unit.html) - -### Enums - -* [EnumBufferOverflowProtectionMode]({{ site.dcvb_enums }}core/buffer-overflow-protection-mode.html?lang=js) -* [EnumCapturedResultItemType]({{ site.dcvb_enums }}core/captured-result-item-type.html?lang=js) -* [EnumColourChannelUsageType]({{ site.dcvb_enums }}core/colour-channel-usage-type.html?lang=js) -* [EnumCornerType]({{ site.dcvb_enums }}core/corner-type.html?lang=js) -* [EnumErrorCode]({{ site.dcvb_enums }}core/error-code.html?lang=js) -* [EnumGrayscaleEnhancementMode]({{ site.dcvb_enums }}core/grayscale-enhancement-mode.html?lang=js) -* [EnumGrayscaleTransformationMode]({{ site.dcvb_enums }}core/grayscale-transformation-mode.html?lang=js) -* [EnumImagePixelFormat]({{ site.dcvb_enums }}core/image-pixel-format.html?lang=js) -* [EnumImageTagType]({{ site.dcvb_enums }}core/image-tag-type.html?lang=js) -* [EnumIntermediateResultUnitType]({{ site.dcvb_enums }}core/intermediate-result-unit-type.html?lang=js) -* [EnumRegionObjectElementType]({{ site.dcvb_enums }}core/region-object-element-type.html?lang=js) -* [EnumSectionType]({{ site.dcvb_enums }}core/section-type.html?lang=js) - -## [DynamsoftLicense]({{ site.dcvb_js_api }}license/license-module.html) - -### Classes - -* [LicenseModule]({{ site.dcvb_js_api }}license/license-module-class.html) -* [LicenseManager]({{ site.dcvb_js_api }}license/license-manager.html) - -## [DynamsoftUtility]({{ site.dcvb_js_api }}utility/utility-module.html) - -### Classes - -* [UtilityModule]({{ site.dcvb_js_api }}utility/utility-module-class.html) -* [ImageManager]({{ site.dcvb_js_api }}utility/image-manager.html) -* [MultiFrameResultCrossFilter]({{ site.dcvb_js_api }}utility//multi-frame-result-cross-filter.html) \ No newline at end of file diff --git a/programming/javascript/api-reference/interfaces/candidate-barcode-zones-unit-v2.0.21.md b/programming/javascript/api-reference/interfaces/candidate-barcode-zones-unit-v2.0.21.md deleted file mode 100644 index 974d7708..00000000 --- a/programming/javascript/api-reference/interfaces/candidate-barcode-zones-unit-v2.0.21.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -layout: default-layout -title: interface CandidateBarcodeZonesUnit - Dynamsoft Barcode Reader Module JS Edition API Reference -description: This page shows the JS edition of the interface CandidateBarcodeZonesUnit in Dynamsoft Barcode Reader Module. -keywords: candidate barcode zone, JS -needAutoGenerateSidebar: true -noTitleIndex: true ---- - -# CandidateBarcodeZonesUnit - -A unit of data related to candidate barcode zones within an image. - -```typescript -interface CandidateBarcodeZonesUnit extends Core.IntermediateResultUnit { - candidateBarcodeZones: Array; -} -``` - - -## candidateBarcodeZones - -An array of `Quadrilateral` objects. Each `Quadrilateral` represents a region or zone within an image that is considered a candidate for containing a barcode. - -```typescript -candidateBarcodeZones: Array; -``` - -**See also** - -* [Quadrilateral]({{ site.dcv_js_api }}core/basic-structures/quadrilateral.html) \ No newline at end of file diff --git a/programming/javascript/api-reference/interfaces/decoded-barcodes-result-v10.5.3000.md b/programming/javascript/api-reference/interfaces/decoded-barcodes-result-v10.5.3000.md deleted file mode 100644 index 1c803771..00000000 --- a/programming/javascript/api-reference/interfaces/decoded-barcodes-result-v10.5.3000.md +++ /dev/null @@ -1,78 +0,0 @@ ---- -layout: default-layout -title: interface DecodedBarcodesResult - Dynamsoft Core Module JS Edition API Reference -description: This page shows the JS edition of the interface DecodedBarcodesResult in Dynamsoft DBR Module. -keywords: decoded barcode, barcode result, item, JS -needAutoGenerateSidebar: true -noTitleIndex: true ---- - -# DecodedBarcodesResult - -Interface DecodedBarcodesResult represents information of decoded barcodes from an image. - -```typescript -interface DecodedBarcodesResult { - readonly originalImageHashId: string; - readonly originalImageTag: Core.ImageTag; - readonly barcodeResultItems: Array; - readonly errorCode: number; - readonly errorString: string; -} -``` - - -## originalImageHashId - -A unique identifier or hash of the original image from which the barcodes were decoded. It can be used to associate the result with a specific input image. - -```typescript -readonly originalImageHashId: string; -``` - -## originalImageTag - -An image tag associated with the original image. - -```typescript -readonly originalImageTag: Core.ImageTag; -``` - -**See also** - -* [ImageTag]({{ site.dcvb_js_api }}core/basic-structures/image-tag.html) - -## barcodeResultItems - -An array of BarcodeResultItem objects, representing the list of decoded barcodes found in the image. - -```typescript -readonly barcodeResultItems: Array; -``` - -**See also** - -* [BarcodeResultItem]({{ site.js_api }}interfaces/barcode-result-item.html) - -## errorCode - -The error code of the barcode reading result, if an error occurred. - -```typescript -readonly errorCode: number; -``` - -## errorString - -The error message of the barcode reading result, if an error occurred. - -```typescript -readonly errorString: string; -``` \ No newline at end of file diff --git a/programming/javascript/api-reference/interfaces/deformation-resisted-barcode-image-unit-v2.0.21.md b/programming/javascript/api-reference/interfaces/deformation-resisted-barcode-image-unit-v2.0.21.md deleted file mode 100644 index e6a246dc..00000000 --- a/programming/javascript/api-reference/interfaces/deformation-resisted-barcode-image-unit-v2.0.21.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -layout: default-layout -title: interface DeformationResistedBarcodeImageUnit - Dynamsoft Barcode Reader Module JS Edition API Reference -description: This page shows the JS edition of the interface DeformationResistedBarcodeImageUnit in Dynamsoft Barcode Reader Module. -keywords: deformation resisted, Image unit, JS -needAutoGenerateSidebar: true -noTitleIndex: true ---- - -# DeformationResistedBarcodeImageUnit - -A unit of data that contains deformation resisted barcode image. It extends the `IntermediateResultUnit` interface. - -```typescript -interface DeformationResistedBarcodeImageUnit extends Core.IntermediateResultUnit { - imageData: Core.DSImageData; -} -``` - - -## imageData - -The image data of the deformation resisted barcode. - -```typescript -imageData: Core.DSImageData; -``` - -**See also** - -* [DSImageData]({{ site.dcv_js_api }}core/basic-structures/ds-image-data.html) \ No newline at end of file diff --git a/programming/javascript/api-reference/interfaces/pdf417-details-v10.5.3000.md b/programming/javascript/api-reference/interfaces/pdf417-details-v10.5.3000.md deleted file mode 100644 index 71e43098..00000000 --- a/programming/javascript/api-reference/interfaces/pdf417-details-v10.5.3000.md +++ /dev/null @@ -1,70 +0,0 @@ ---- -layout: default-layout -title: interface PDF417Details - Dynamsoft Core Module JS Edition API Reference -description: This page shows the JS edition of the interface PDF417Details in Dynamsoft DBR Module. -keywords: PDF417 details, JS -needAutoGenerateSidebar: true -noTitleIndex: true ---- - -# PDF417Details - -This interface extends `BarcodeDetails` interface and adds properties specific to PDF417 barcodes such as `rows`, `columns`, `errorCorrectionLevel`, etc. - -```typescript -interface PDF417Details extends BarcodeDetails { - rows: number; - columns: number; - errorCorrectionLevel: number; - hasLeftRowIndicator: number; - hasRightRowIndicator: number; -} -``` - - -## rows - -The row count of the PDF417 barcode, indicating how many rows of modules it contains. - -```typescript -rows: number; -``` - -## columns - -The column count of the PDF417 barcode, indicating how many columns of modules it contains. - -```typescript -columns: number; -``` - -## errorCorrectionLevel - -The error correction level of the PDF417 barcode. - -```typescript -errorCorrectionLevel: number; -``` - -## hasLeftRowIndicator - -Indicates whether the PDF417 code has a left row indicator (1 means yes, 0 means no). Row indicators are used to denote the start of a new row in the barcode. - -```typescript -hasLeftRowIndicator: number; -``` - -## hasRightRowIndicator - -Indicates whether the PDF417 code has a right row indicator (1 means yes, 0 means no). Similar to the left row indicator, the right row indicator is used to denote the end of a row in the barcode. - -```typescript -hasRightRowIndicator: number; -``` \ No newline at end of file diff --git a/programming/javascript/api-reference/interfaces/qr-code-details-v10.2.10.md b/programming/javascript/api-reference/interfaces/qr-code-details-v10.2.10.md deleted file mode 100644 index b3d9428a..00000000 --- a/programming/javascript/api-reference/interfaces/qr-code-details-v10.2.10.md +++ /dev/null @@ -1,111 +0,0 @@ ---- -layout: default-layout -title: interface QR CodeDetails - Dynamsoft Core Module JS Edition API Reference -description: This page shows the JS edition of the interface QR CodeDetails in Dynamsoft DBR Module. -keywords: QR Code details, JS -needAutoGenerateSidebar: true -noTitleIndex: true ---- - -# QRCodeDetails - -This interface extends `BarcodeDetails` interface and adds properties specific to QR barcodes such as `rows`, `columns`, `errorCorrectionLevel`, etc. - -```typescript -interface QRCodeDetails extends BarcodeDetails { - rows: number; - columns: number; - errorCorrectionLevel: number; - version: number; - model: number; - mode: number; - page: number; - totalPage: number; - parityData: number; -} -``` - - - -## rows - -The row count of the QR Code, indicating how many rows of modules it contains. - -```typescript -rows: number; -``` - -## columns - -The column count of the QR Code, indicating how many columns of modules it contains. - -```typescript -columns: number; -``` - -## errorCorrectionLevel - -The error correction level of the QR Code. - -```typescript -errorCorrectionLevel: number; -``` - -## version - -The version of the QR code. QR codes come in different versions, each with varying data capacities and sizes. - -```typescript -version: number; -``` - -## model - -Number of models of the QR Code. - -```typescript -model: number; -``` - -## mode - -Identify the first data encoding mode of the QR Code. - -```typescript -mode: number; -``` - -## page - -Position of the particular symbol in the Structured Append format of the QR Code. - -```typescript -page: number; -``` - -## totalPage - -Identify the total number of symbols to be concatenated in the Structured Append format of the QR Code. - -```typescript -totalPage: number; -``` - -## parityData - -A value obtained by XORing byte by byte the ASCII/JIS values of all the original input data before division into symbol blocks. It's used for error checking and correction. - -```typescript -parityData: number; -``` \ No newline at end of file diff --git a/programming/javascript/index-v10.4.3100.md b/programming/javascript/index-v10.4.3100.md deleted file mode 100644 index 55f989f2..00000000 --- a/programming/javascript/index-v10.4.3100.md +++ /dev/null @@ -1,88 +0,0 @@ ---- -layout: default-layout -title: Introduction - Dynamsoft Barcode Reader JavaScript Edition -description: This is introduction page of Dynamsoft Barcode Reader JavaScript SDK version 10.0.21. -keywords: javascript, js -needAutoGenerateSidebar: true -needGenerateH3Content: true -noTitleIndex: false -breadcrumbText: JavaScript ---- - -# Introduction to Dynamsoft Barcode Reader JavaScript Edition version 10.x - -Dynamsoft Barcode Reader (DBR) can be used in JavaScript to add barcode reading capabilities to websites running in modern browsers. It is ideal for - -* organizations who already have sophisticated websites and do not intend to develop mobile applications for the same purposes; or -* organizations whose customers have no desire to install applications for temporary usage of their services. - -To get a fast start, you can - -* read the [User Guide](user-guide/), or -* try the [Samples and Demos](samples-demos/) - -The following describes the highlights of DBR JavaScript edition (DBR-JS) version 10.x. - -## Fast Integration - -This [JSFiddle example](https://jsfiddle.net/DynamsoftTeam/csm2f9wb/) demonstrates all the code needed to build a web application using DBR, end users of the web page can open it in a browser, access their cameras and read barcodes directly from the video input. - -### Camera Control - -Customers generally need to scan a barcode on the fly at which time there is no better input than the camera hooked to or built into the device itself. As shown in the code snippet above, the product **Dynamsoft Camera Enhancer (DCE)** is used to provide camera support. It makes use of the powerful [**MediaDevices**](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices) interface (provided by the browser itself) to instantly access the video input of the camera, capture image frames and supply them to the back-end decoding engine. - -> DBR and DCE communicate through the interface called [Image Source Adapter]({{ site.dcvb_architecture }}input.html#image-source-adapter?lang=js). - -### Interactive UI - -Good interaction design is essential for a website. With the help of DCE, the barcode reading process is made interactive as shown in the screenshot below. - -![Interactive UI](assets/interactive-ui.png) - -## High Performance - -Barcode reading is usually just an auxiliary way to assist a small step in a complex workflow. Customers like the convenience, but if it takes too long or is error-prone, their patience will quickly run out. Therefore, high performance is crucial. - -### Unparalleled Speed - -DBR showcases Dynamsoft's cutting-edge technology in light-speed recognition of barcodes. In most cases, an image gets deblurred, binarized and read under 100 milliseconds. - -With the help of DCE JS, DBR no longer wastes time on image capture and often gets high-quality images for processing, which further increases its speed. - -### Proficiency in Handling Difficult Environments - -The actual use environment is unpredictable. The barcode may appear distorted, inverted, or partially damaged; the background may be textured or spotted; the light may be very low, and there may be shadows and glare. DBR handles all these cases with its rich image processing algorithms through various adjustable settings. - -### Exceptional Accuracy - -DBR does a lot of preparation work to make sure the barcode is as legible as possible for the decoding engine to read. This ensures a very high accuracy. In addition, DBR achieves even higher accuracy through the following ways: - -* DBR can verify results by comparing the results of multiple consecutive recognitions; -* DBR has a confidence score for each recognition which can be used to filter unwanted results; -* DBR is also able to verify the barcode result with printed text that accompanies the barcode with the help of the product **Dynamsoft Label Recognizer (DLR)**. - -Through many experiences, DBR has also cultivated its error correction ability to handle - -* Non-standard barcodes which do not strictly abide by the specification; -* Deformed barcodes which are usually caused by improper printing. - -## Effortless Expansion - -DBR-JS v10.x is based on [Dynamsoft Capture Vision]({{site.dcvb_architecture}}) which is a modular architecture. This architecture makes it easy to add new functionality or custom behavior with very little change to the code. Two examples are: - -* Add **Dynamsoft Document Normalizer (DDN)** to do perspective correction before pass an image frame to read barcodes; -* Add **Dynamsoft Code Parser (DCP)** to parse the text embedded in the PDF417 on driver's licenses. - -## Next Step - -Read the [User Guide](user-guide/) to start building your own websites with barcode reading capabilities. - -## See Also - -### API Reference - -For an overview of the APIs, see the [API Reference](api-reference/). - -### Release Notes - -For a peek of DBR-JS history, check the [Release Notes](release-notes/). diff --git a/programming/javascript/index-v10.5.3000.md b/programming/javascript/index-v10.5.3000.md deleted file mode 100644 index 0a2d97c4..00000000 --- a/programming/javascript/index-v10.5.3000.md +++ /dev/null @@ -1,105 +0,0 @@ ---- -layout: default-layout -title: Introduction - Dynamsoft Barcode Reader JavaScript Edition -description: This is introduction page of Dynamsoft Barcode Reader JavaScript SDK version 10.0.21. -keywords: javascript, js -needAutoGenerateSidebar: true -needGenerateH3Content: true -noTitleIndex: true -breadcrumbText: JavaScript ---- - -# Introduction to Dynamsoft Barcode Reader JavaScript Edition version 10.x - -Dynamsoft Barcode Reader (DBR) can be used in JavaScript to add barcode reading capabilities to websites running in modern browsers. It is ideal for - -* organizations who already have sophisticated websites and do not intend to develop mobile applications for the same purposes; or -* organizations whose customers have no desire to install applications for temporary usage of their services. - -To get a fast start, you can - -* read the [User Guide](user-guide/barcode-scanner.html), or -* try the [Samples and Demos](samples-demos/) - -The following describes the highlights of DBR JavaScript edition (DBR-JS) version 10.x. - -# ✨New in v10.5.3000: BarcodeScanner – Simplified API and Built-in UI - -Version 10.5.3000 introduces the all-new `BarcodeScanner` class, offering a streamlined API and a prebuilt interactive UI, making barcode scanning integration easier than ever. This is now the recommended way to use DBR-JS, especially for developers who want a quick, clean, and robust scanning experience with minimal setup. - -With `BarcodeScanner`, you can: - -- Instantiate and configure the scanner with just a few lines of code; - -- Select your scanning mode and present a ready-to-use scanning interface; - -- Focus on your application logic without worrying about camera setup, UI rendering, or lifecycle management. - -> [!TIP] -> You can either get a [quick start with the BarcodeScanner APIs](user-guide/barcode-scanner.html) or experience a highly customizable [development with the foundational APIs](user-guide/index.html). If you're just starting out, we highly recommend using the `BarcodeScanner` class for the best balance of simplicity, performance, and user experience. - ---- - -## Fast Integration - -This [JSFiddle example](https://jsfiddle.net/DynamsoftTeam/gcqjf5r7/) demonstrates all the code needed to build a web application using `BarcodeScanner`, end users of the web page can open it in a browser, access their cameras and read barcodes directly from the video input. - -### Camera Control - -Customers generally need to scan a barcode on the fly at which time there is no better input than the camera hooked to or built into the device itself. As shown in the code snippet above, the product **Dynamsoft Camera Enhancer (DCE)** is used to provide camera support. It makes use of the powerful [**MediaDevices**](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices) interface (provided by the browser itself) to instantly access the video input of the camera, capture image frames and supply them to the back-end decoding engine. - -> DBR and DCE communicate through the interface called [Image Source Adapter]({{ site.dcvb_architecture }}input.html#image-source-adapter?lang=js). - -### Interactive UI - -Good interaction design is essential for a website. With the help of DCE, the barcode reading process is made interactive as shown in the screenshot below. - -![Interactive UI](assets/interactive-ui.png) - -## High Performance - -Barcode reading is usually just an auxiliary way to assist a small step in a complex workflow. Customers like the convenience, but if it takes too long or is error-prone, their patience will quickly run out. Therefore, high performance is crucial. - -### Unparalleled Speed - -DBR showcases Dynamsoft's cutting-edge technology in light-speed recognition of barcodes. In most cases, an image gets deblurred, binarized and read under 100 milliseconds. - -With the help of DCE JS, DBR no longer wastes time on image capture and often gets high-quality images for processing, which further increases its speed. - -### Proficiency in Handling Difficult Environments - -The actual use environment is unpredictable. The barcode may appear distorted, inverted, or partially damaged; the background may be textured or spotted; the light may be very low, and there may be shadows and glare. DBR handles all these cases with its rich image processing algorithms through various adjustable settings. - -### Exceptional Accuracy - -DBR does a lot of preparation work to make sure the barcode is as legible as possible for the decoding engine to read. This ensures a very high accuracy. In addition, DBR achieves even higher accuracy through the following ways: - -* DBR can verify results by comparing the results of multiple consecutive recognitions; -* DBR has a confidence score for each recognition which can be used to filter unwanted results; -* DBR is also able to verify the barcode result with printed text that accompanies the barcode with the help of the product **Dynamsoft Label Recognizer (DLR)**. - -Through many experiences, DBR has also cultivated its error correction ability to handle - -* Non-standard barcodes which do not strictly abide by the specification; -* Deformed barcodes which are usually caused by improper printing. - -## Effortless Expansion - -DBR-JS v10.x is based on [Dynamsoft Capture Vision]({{site.dcvb_architecture}}) which is a modular architecture. This architecture makes it easy to add new functionality or custom behavior with very little change to the code. Two examples are: - -* Add **Dynamsoft Document Normalizer (DDN)** to do perspective correction before pass an image frame to read barcodes; -* Add **Dynamsoft Code Parser (DCP)** to parse the text embedded in the PDF417 on driver's licenses. - -## Next Step - -Read the [User Guide](user-guide/barcode-scanner.html) to start building your own websites with barcode reading capabilities. - -## See Also - -### API Reference - -For an overview of the APIs, see the [API Reference](api-reference/barcode-scanner.html). - -### Release Notes - -For a peek of DBR-JS history, check the [Release Notes](release-notes/). diff --git a/programming/javascript/release-notes/index.md b/programming/javascript/release-notes/index.md index 6582a2fa..1b620133 100644 --- a/programming/javascript/release-notes/index.md +++ b/programming/javascript/release-notes/index.md @@ -5,7 +5,6 @@ description: This is the release notes page of Dynamsoft Barcode Reader JavaScri keywords: release notes, javascript needAutoGenerateSidebar: false breadcrumbText: Release Notes -permalink: /programming/javascript/release-notes/index.html --- # DBR JavaScript SDK - Release Notes diff --git a/programming/javascript/release-notes/js-9.md b/programming/javascript/release-notes/js-9.md index e4721774..57bd1ddf 100644 --- a/programming/javascript/release-notes/js-9.md +++ b/programming/javascript/release-notes/js-9.md @@ -112,7 +112,7 @@ permalink: /programming/javascript/release-notes/js-9.html #### Improved - Updated the barcode reader algorithm to v9.6.10. -- Updated the internal `Dynamsoft Camera Enhancer` to [v3.3.1](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/release-note/release-notes-3.x.html#331-02202023). +- Updated the internal `Dynamsoft Camera Enhancer` to [v3.3.1](https://www.dynamsoft.com/camera-enhancer/docs-archive/web/programming/javascript/release-note/release-notes-3.x.html#331-02202023). - The method [`decodeBuffer`](../api-reference/BarcodeReader.md#decodebuffer) is updated to accept an additional parameter "orientation" to help specify the orientation of the image data. - The interface [`LocalizationResult`](../api-reference/interface/LocalizationResult.md) is updated to have a new property "transformationMatrix". - Three missing errorcodes are added: DBR_PANORAMA_LICENSE_INVALID, DBR_PHARMACODE_LICENSE_INVALID, DBR_IMAGE_ORIENTATION_INVALID. Check the full list at [`EnumErrorCode`](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/enum/EnumErrorCode.html). @@ -197,7 +197,7 @@ permalink: /programming/javascript/release-notes/js-9.html ## 9.2.12 (08/04/2022) * Fixed a bug where the scan region mask and/or other shapes drawn on the UI were not updated when the view changed to landscape from portrait or vice versa on mobile devices. -* This version uses [Dynamsoft Camera Enhancer version 3.0.1](https://www.dynamsoft.com/camera-enhancer/docs/programming/javascript/release-note/release-notes-3.x.html?ver=latest#301-08042022). +* This version uses [Dynamsoft Camera Enhancer version 3.0.1](https://www.dynamsoft.com/camera-enhancer/docs-archive/web/programming/javascript/release-note/release-notes-3.x.html?ver=latest#301-08042022). ## 9.2.11 (07/28/2022) @@ -213,7 +213,7 @@ permalink: /programming/javascript/release-notes/js-9.html * The method `setImageSource()` now takes an additional parameter `options` which helps to pass the information needed by the `BarcodeReader` object, such as the definition (`Dynamsoft.DCE.DrawingItem`) for creating the shapes that highlight barcodes. * When reading 1D barcodes, the callback `onFrameRead` now verifies a result across multiple frames before outputting it so that it is more reliable. The same logic was always used for the callback `onUniqueRead`. * The methods `pauseScan()` (for `BarcodeScanner`) and `pauseScanning()` (for `BarcodeReader`) now both accept an optional parameter `options`, which can control the behavior of the pause, such as whether to keep results highlighted (`keepResultsHighlighted`). -* This version uses [Dynamsoft Camera Enhancer version 3.0.0](https://www.dynamsoft.com/camera-enhancer/docs/programming/javascript/release-note/release-notes-3.x.html#300-07272022) instead of the previous version 2.3.2. +* This version uses [Dynamsoft Camera Enhancer version 3.0.0](https://www.dynamsoft.com/camera-enhancer/docs-archive/web/programming/javascript/release-note/release-notes-3.x.html#300-07272022) instead of the previous version 2.3.2. ### Fixed diff --git a/programming/javascript/samples-demos/index-v10.4.3100.md b/programming/javascript/samples-demos/index-v10.4.3100.md deleted file mode 100644 index f4671783..00000000 --- a/programming/javascript/samples-demos/index-v10.4.3100.md +++ /dev/null @@ -1,188 +0,0 @@ ---- -layout: default-layout -title: Samples and Demos Index - Dynamsoft Barcode Reader JavaScript Edition -description: Refer these samples and demos for different frameworks such as Angular, React, NuxtJS, etc, of Dynamsoft Barcode Reader JavaScript Edition. -keywords: javascript, js -breadcrumbText: Samples and Demos -noTitleIndex: true -needAutoGenerateSidebar: false ---- - - - diff --git a/programming/javascript/samples-demos/index-v11.0.3000.md b/programming/javascript/samples-demos/index-v11.0.3000.md deleted file mode 100644 index 0c466488..00000000 --- a/programming/javascript/samples-demos/index-v11.0.3000.md +++ /dev/null @@ -1,310 +0,0 @@ ---- -layout: default-layout -title: Samples and Demos Index - Dynamsoft Barcode Reader JavaScript Edition -description: Refer these samples and demos for different frameworks such as Angular, React, NuxtJS, etc, of Dynamsoft Barcode Reader JavaScript Edition. -keywords: javascript, js -breadcrumbText: Samples and Demos -noTitleIndex: true -needAutoGenerateSidebar: false ---- - - - \ No newline at end of file diff --git a/programming/javascript/upgrade-guide/7-notice.md b/programming/javascript/upgrade-guide/7-notice.md deleted file mode 100644 index ac9d9b45..00000000 --- a/programming/javascript/upgrade-guide/7-notice.md +++ /dev/null @@ -1,43 +0,0 @@ ---- -layout: default-layout -title: END OF SUPPORT for version 7 of Dynamsoft Barcode Reader JavaScript Edition -description: Dynamsoft Barcode Reader JavaScript Edition v7.x maintenance is ending on 2023/12/31, upgrade is recommended. -keywords: user guide, upgrade, javascript, js, v7, end of support -needAutoGenerateSidebar: true -permalink: /programming/javascript/upgrade-guide/7-notice.html -noTitleIndex: true ---- - -# Dynamsoft Barcode Reader JavaScript Edition Version 7.x Will Reach End of Support on December 31st 2023 - -First released on August 09th, 2019, Dynamsoft Barcode Reader JavaScript Edition Version 7.x (DBR-JS 7) had 11 minor updates in total. Version 7.6.0 was the final version of DBR-JS 7 and it was released on September 1st, 2020. - -Based on Dynamsoft Lifetime Support Policy, Dynamsoft is committed to providing maintenance and support for all Dynamsoft product releases for TWO years from their general availability date. - -DBR-JS 7 was well accepted by hundreds of customers and we extended its maintenance and support after it had reached TWO years on August 31st, 2022. However, it will reach end of support by end of this year. This means that Dynamsoft will no longer be providing updates, bug fixes, or technical support for this version beyond 2023/12/31. - -Since the date is fast approaching, our system will stop serving new licenses for DBR-JS 7, including validity extensions or quota extensions. The license server that supports DBR-JS 7 will be taken offline by end of 2024. If you already have a license for DBR-JS 7 beyond that time and would like to keep using it, you can [contact us](https://www.dynamsoft.com/contact/). - -## Upgrade is recommended - -If you are still using DBR-JS 7, We strongly recommend that you upgrade to our latest v9.6, which offers many new features and improvements. - -### What's New? - -- Improved recognition success rate and speed for linear barcodes -- Faster processing of continuous video frames -- Improved camera control, especially on android devices. For example, auto zoom and auto focus. -- Support for many more barcode types including Pharma Code, Code 11, MSI, etc. -- Other features and bug fixes - -### Try Online Demo - -We invite you to try our [online demo](https://demo.dynamsoft.com/barcode-reader-js) to see the latest version in action. - -### Free Upgrade from v7 to v9 - -If you have a subscription license, the upgrade is free of charge. Otherwise, you can [contact us](https://www.dynamsoft.com/contact/) for a paid upgrade. - -We understand that upgrading to a new version can be a significant undertaking. Our support team is available to assist you if you encounter any issues during the upgrade process. - -[Step by step upgrade guide >](7to9.md) \ No newline at end of file diff --git a/programming/javascript/upgrade-guide/7to9.md b/programming/javascript/upgrade-guide/7to9.md deleted file mode 100644 index fb440dbf..00000000 --- a/programming/javascript/upgrade-guide/7to9.md +++ /dev/null @@ -1,115 +0,0 @@ ---- -layout: default-layout -title: Upgrade guide for version 7 to 9 - Dynamsoft Barcode Reader JavaScript Edition -description: This page shows how to upgrade Dynamsoft Barcode Reader JavaScript SDK from version 7 to 9. -keywords: user guide, upgrade, javascript, js -needAutoGenerateSidebar: true -pageStartVer: 8.4 -permalink: /programming/javascript/upgrade-guide/7to9.html -noTitleIndex: false ---- - -# How to Upgrade DBR-JS From v7.x To v9.x - -## Change your license - - Your v7.x license is not compatible with v9.x, you must [Contact Dynamsoft Sales Team](mailto:sales@dynamsoft.com) to acquire a new license key. If you have a subscription license or you have valid maintenance for a perpetual license, the upgrade is free of charge. - -## Update the version number if you are using a **CDN** - - ```html - - ``` - - > If you have deployed the library files to your own server, [download the latest version](https://www.dynamsoft.com/barcode-reader/downloads/?utm_source=upgradeguide) and replace the old files. - -## Update the API you use for licensing the SDK - - In v7.x, you probably licensed the SDK with "data-productKeys" like this: - - ```html - - ``` - - In v9.x, use the API `license` instead: - - ```html - - ``` - -## Breaking Changes - -### :exclamation: *Namespace change* - -Use the new namespace `Dynamsoft.DBR` in place of just `Dynamsoft`. The following shows the equivalent changes for `BarcodeScanner` and `BarcodeReader`: - -```js -Dynamsoft.BarcodeScanner -> Dynamsoft.DBR.BarcodeScanner -Dynamsoft.BarcodeReader -> Dynamsoft.DBR.BarcodeReader -``` - -> If you are using the library as an ES/CMD module, you don't need to change your code.Otherwise, you can make a global change from `Dynamsoft` to `Dynamsoft.DBR` in your code. - -### API Changes - -After changing the namespace, check your code and see if you are using any of the APIs in the first column below. If found, change them to the equivalent shown in the second column: - -| API Name | Notes | -|:-:|:-:| -| `Dynamsoft.DBR.detectEnvironment()` | Use `Dynamsoft.DBR.BarcodeReader.detectEnvironment()` instead. | -| `Dynamsoft.DBR.engineResourcePath` | Use `Dynamsoft.DBR.BarcodeReader.engineResourcePath` instead. | -| `Dynamsoft.DBR.isLoaded()` | Use `Dynamsoft.DBR.BarcodeReader.isWasmLoaded()` instead. | -| `Dynamsoft.DBR.loadWasm()` | Use `Dynamsoft.DBR.BarcodeReader.loadWasm()` instead. | -| `Dynamsoft.DBR.productKeys` | Use `Dynamsoft.DBR.BarcodeReader.license` instead. | -| `Dynamsoft.DBR.version` | Use `Dynamsoft.DBR.BarcodeReader.version` instead. | -| `destroy()` | Use `destroyContext()` instead. | -| `bDestroyed` | Use `isContextDestroyed()` instead. | -| `onUnduplicatedRead` | Use `onUniqueRead` instead. | -| `bPlaySoundOnSuccessfulRead` | Use `whenToPlaySoundforSuccessfulRead` in `ScanSettings` instead. | -| `soundOnSuccessfulRead` | Use `soundOnSuccessfullRead` in `ScanSettings` instead. | -| `bSaveOriCanvas` | Use `ifSaveOriginalImageInACanvas` instead. | -| `oriCanvas` | Use `getOriginalImageInACanvas()` instead. | - -### `deblurLevel` is Deprecated - -`deblurLevel` has been replaced with `deblurModes`. - -Check out the code below on how to switch from `deblurLevel` to `deblurModes`. - -```js -let settings = await barcodeScanner.getRuntimeSettings(); -//settings.deblurLevel = 9; -settings.deblurModes = ["DM_DIRECT_BINARIZATION", - "DM_THRESHOLD_BINARIZATION", - "DM_GRAY_EQUALIZATION", - "DM_SMOOTHING", - "DM_MORPHING", - "DM_DEEP_ANALYSIS", - "DM_SHARPENING", - "DM_SKIP"] -await barcodeScanner.updateRuntimeSettings(settings); -``` - -### Changed Class Names of the Built-in UI elements - -If you manipulated any of the built-in UI elements which are located by their class names, you need to update the class name(s) used in your code. - -| v7.x in **dbr.scanner.html** | v9.x in **dbr.ui.html**| -|:-:|:-:| -| `dbrScanner-bg-loading` | `dce-bg-loading` | -| `dbrScanner-bg-camera` | `dce-bg-camera` | -| `dbrScanner-video` | `dce-video` | -| `dbrScanner-cvs-scanarea` | `dce-scanarea` | -| `dbrScanner-scanlight` | `dce-scanlight` | -| `dbrScanner-sel-camera` | `dce-sel-camera` | -| `dbrScanner-sel-resolutio` | `dce-sel-resolution` | -| `dbrScanner-btn-close` | `dce-btn-close` | - -### Other changes - -The file **dbr.scanner.html** has been renamed to **dbr.ui.html**. - -If you are still having issue with the upgrade, please [contact us](https://www.dynamsoft.com/contact/). diff --git a/programming/javascript/upgrade-guide/8to9.md b/programming/javascript/upgrade-guide/8to9.md deleted file mode 100644 index da5ab207..00000000 --- a/programming/javascript/upgrade-guide/8to9.md +++ /dev/null @@ -1,79 +0,0 @@ ---- -layout: default-layout -title: Upgrade guide to version 9 - Dynamsoft Barcode Reader JavaScript Edition -description: This page shows how to upgrade Dynamsoft Barcode Reader JavaScript SDK up till v9.x. -keywords: user guide, upgrade, javascript, js -needAutoGenerateSidebar: true -pageStartVer: 8.4 -permalink: /programming/javascript/upgrade-guide/8to9.html ---- - -# How to Upgrade DBR-JS from v8.x to v9.x - -1. Update the version number if you are using a **CDN**: - - ```html - - ``` - - > If you have deployed the library files to your own server, [download the latest version](https://www.dynamsoft.com/barcode-reader/downloads/?utm_source=upgradeguide) and replace the old files. - -2. Update the API you use for licensing the SDK - -Previously, you might have used the APIs `productKeys`, `handshakeCode`, `organizationID` and `sessionPassword`, etc. In v9.0.0+, use the API `license` instead. - -* If you used an offline license before, simply pass that license key using the API `license`. -* If you used an online license before, you can log in the [customer portal](https://www.dynamsoft.com/customer/license/fullLicense) and check the according license key to be used with the API `license`. - -[Contact Dynamsoft Sales Team](mailto:sales@dynamsoft.com) for more information. - -### Breaking changes introduced in v9.0.0 - -* The following APIs are renamed: - -| Old API | New API | -|:-:|:-:| -| `onUnduplicatedRead` | `onUniqueRead` | -| `outputSettingsToString()` | `outputRuntimeSettingsToString()` | -| `Dynamsoft.DBR.BarcodeReader.isLoaded()` | `Dynamsoft.DBR.BarcodeReader.isWasmLoaded()` | - -* The following APIs are removed: - -| API Name | Notes | -|:-:|:-:| -| `Dynamsoft.DBR.browserInfo` | Use `Dynamsoft.DBR.BarcodeReader.browserInfo` instead. | -| `Dynamsoft.DBR.detectEnvironment()` | Use `Dynamsoft.DBR.BarcodeReader.detectEnvironment()` instead. | -| `Dynamsoft.DBR.deviceFriendlyName` | Use `Dynamsoft.DBR.BarcodeReader.deviceFriendlyName` instead. | -| `Dynamsoft.DBR.engineResourcePath` | Use `Dynamsoft.DBR.BarcodeReader.engineResourcePath` instead. | -| `Dynamsoft.DBR.handshakeCode` | Use `Dynamsoft.DBR.BarcodeReader.license` instead. | -| `Dynamsoft.DBR.isLoaded()` | Use `Dynamsoft.DBR.BarcodeReader.isWasmLoaded()` instead. | -| `Dynamsoft.DBR.licenseServer` | Use `Dynamsoft.DBR.BarcodeReader.license` instead. | -| `Dynamsoft.DBR.loadWasm()` | Use `Dynamsoft.DBR.BarcodeReader.loadWasm()` instead. | -| `Dynamsoft.DBR.organizationID` | Use `Dynamsoft.DBR.BarcodeReader.license` instead. | -| `Dynamsoft.DBR.productKeys` | Use `Dynamsoft.DBR.BarcodeReader.license` instead. | -| `Dynamsoft.DBR.sessionPassword` | Use `Dynamsoft.DBR.BarcodeReader.license` instead. | -| `Dynamsoft.DBR.version` | Use `Dynamsoft.DBR.BarcodeReader.version` instead. | - -* The following APIs are moved: - -| API Name | Notes | -|:-:|:-:| -| `whenToPlaySoundforSuccessfulRead` | Moved to [ScanSettings](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/interface/ScanSettings.html). | -| `soundOnSuccessfullRead` | Moved to [ScanSettings](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/interface/ScanSettings.html). | -| `whenToVibrateforSuccessfulRead` | Moved to [ScanSettings](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/interface/ScanSettings.html). | -| `vibrateDuration` | Moved to [ScanSettings](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/interface/ScanSettings.html). | - -* The file **dbr.scanner.html** has been renamed to **dbr.ui.html**. - -### Breaking changes introduced in v8.8.0 - -The class names of the built-in UI elements changed in v8.8.0+: - -| Previous versions | v8.8.0+ | -|:-:|:-:| -| `dbrScanner-bg-loading` | `dce-bg-loading` | -| `dbrScanner-bg-camera` | `dce-bg-camera` | -| `dbrScanner-video` | `dce-video` | -| `dbrScanner-sel-camera` | `dce-sel-camera` | -| `dbrScanner-sel-resolutio` | `dce-sel-resolution` | -| `dbrScanner-btn-close` | `dce-btn-close` | diff --git a/programming/javascript/upgrade-guide/9to10.md b/programming/javascript/upgrade-guide/9to10.md deleted file mode 100644 index 76c75fb4..00000000 --- a/programming/javascript/upgrade-guide/9to10.md +++ /dev/null @@ -1,303 +0,0 @@ ---- -layout: default-layout -title: Upgrade guide for version 9 to 10 - Dynamsoft Barcode Reader JavaScript Edition -description: This page shows how to upgrade Dynamsoft Barcode Reader JavaScript SDK from version 9 to 10. -keywords: user guide, upgrade, javascript, js -needAutoGenerateSidebar: true -permalink: /programming/javascript/upgrade-guide/9to10.html ---- - -# How to Upgrade DBR-JS from v9.x to v10.x - -Version 10 of the Dynamsoft Barcode Reader JavaScript edition has undergone a comprehensive overhaul to align with the Dynamsoft Capture Vision architecture. To understand the advantages of this new architecture, please refer to these resources: - -* [Overview of Dynamsoft Capture Vision](https://www.dynamsoft.com/capture-vision/docs/core/introduction/) -* [Dynamsoft Capture Vision Framework Details](https://www.dynamsoft.com/capture-vision/docs/core/architecture/) - -Additionally, it's important to note that Dynamsoft's ongoing enhancements will be based on this updated architecture. By upgrading to version 10 and adopting the new framework concurrently, you will gain access to the latest features and enhanced performance. - -Due to these significant changes, a substantial rewrite of your existing code will be necessary to transition to the new version. This document will provide guidance throughout this upgrading process. - -> NOTE -> -> In this guide, we assume the following -> 1. The `BarcodeReader` or `BarcodeScanner` instance is called `reader` or `scanner` respectively; -> 2. The `CaptureVisionRouter` instance is called `cvRouter`; -> 3. The `CameraEnhancer` instance is called `cameraEnhancer`; -> 4. The `CameraView` instance is called `cameraView`. - -## Change the way to reference the SDK - -In version 9.x, you only need one line of code: - -```html - -``` - -In version 10.x, you may need to reference several modules: - -```html - - - - - - -``` - -In version 10.0.21 and above, you can also just use this line for simplicity: - -```html - -``` - -## Change the APIs for initializing - -### License - -> IMPORTANT INFORMATION -> -> Users with a time-limited license for version 8 or newer can utilize their existing license for version 10. However, if you possess a permanent license or a time-limited license for version 7 or earlier, a license update may be required. For further details, please reach out to [Dynamsoft Sales](sales@dynamsoft.com). - -In version 10, license control is taken over by the "License" module: - -| API in v9.x | API in v10.x | -| ------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `Dynamsoft.DBR.BarcodeReader.license` | [Dynamsoft.License.LicenseManager.initLicense()](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/license/license-manager.html?product=dbr&repoType=web#initlicense) | -| `Dynamsoft.DBR.BarcodeReader.deviceFriendlyName` | [Dynamsoft.License.LicenseManager.setDeviceFriendlyName()](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/license/license-manager.html?product=dbr&repoType=web#setdevicefriendlyname) | - -The new module also added the following method: - -* [Dynamsoft.License.LicenseManager.getDeviceUUID()](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/license/license-manager.html?product=dbr&repoType=web#getdeviceuuid) - -### Others - -APIs for setting up the SDK have been taken over by the new classes `CaptureVisionRouter`, `CaptureVisionRouterModule` or `BarcodeReaderModule`: - -| API in v9.x | API in v10.x | -| -------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `Dynamsoft.DBR.BarcodeReader.engineResourcePath` or
`Dynamsoft.DBR.BarcodeScanner.engineResourcePath` | [Dynamsoft.Core.CoreModule.engineResourcePaths](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/core/core-module-class.html?product=dbr&repoType=web#engineresourcepaths) | -| `Dynamsoft.DBR.BarcodeReader.loadWasm()` or
`Dynamsoft.DBR.BarcodeScanner.loadWasm()` | [Dynamsoft.Core.CoreModule.loadWasm(["cvr", "dbr"])](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/core/core-module-class.html?product=dbr&repoType=web#loadwasm) | -| `Dynamsoft.DBR.BarcodeReader.isWasmLoaded()` or
`Dynamsoft.DBR.BarcodeScanner.isWasmLoaded()` | [Dynamsoft.Core.CoreModule.isModuleLoaded('dbr')](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/core/core-module-class.html?product=dbr&repoType=web#ismoduleloaded) | -| `Dynamsoft.DBR.BarcodeReader.version` or
`Dynamsoft.DBR.BarcodeScanner.version` | [Dynamsoft.DBR.BarcodeReaderModule.getVersion()](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/barcode-reader-module.html#getversion) | -| `Dynamsoft.DBR.BarcodeReader.detectEnvironment()` or
`Dynamsoft.DBR.BarcodeScanner.detectEnvironment()` | [Dynamsoft.Core.CoreModule.detectEnvironment()](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/core/core-module-class.html?product=dbr&repoType=web#detectenvironment) | -| `Dynamsoft.DBR.BarcodeReader.onWarning` or
`Dynamsoft.DBR.BarcodeScanner.onWarning` | [Dynamsoft.Core.CoreModule.onWarning](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/core/core-module-class.html#onwarning) and
[Dynamsoft.DCE.CameraEnhancer.onWarning](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/instantiate.html?product=dbr&repoType=web#onwarning) | -| `Dynamsoft.DBR.BarcodeReader.createInstance()`or
`Dynamsoft.DBR.BarcodeScanner.createInstance()` | [Dynamsoft.CVR.CaptureVisionRouter.createInstance()](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/capture-vision-router/instantiate.html?product=dbr&repoType=web#createinstance) | - -| API in v9.x | API in v10.x | -| ------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `reader.destroyContext()` or
`scanner.destroyContext()` | [cvRouter.dispose()](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/capture-vision-router/instantiate.html?product=dbr&repoType=web#dispose) | -| `reader.isContextDestroyed()` or
`scanner.isContextDestroyed()` | [cvRouter.disposed](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/capture-vision-router/instantiate.html?product=dbr&repoType=web#disposed) | - - -## Change the APIs for image processing - -### Single-Image processing - -| API in v9.x | API in v10.x | -| ------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `reader.decode()` or
`scanner.decode()` | [cvRouter.capture()](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/capture-vision-router/single-file-processing.html?product=dbr&repoType=web#capture) that specifies a template for barcode reading. | - -### Multiple-Image processing - -| API in v9.x | API in v10.x | -| --------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `reader.setImageSource()` | [cvRouter.setInput()](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/capture-vision-router/multiple-image-processing.html?product=dbr&repoType=web#setinput) | -| `reader.onImageRead` or
`scanner.onFrameRead` | `let resultReceiver = new Dynamsoft.CVR.CapturedResultReceiver();`
`resultReceiver.onDecodedBarcodesReceived = result => { };`
`cvRouter.addResultReceiver(resultReceiver)` | -| `reader.onUniqueRead` or
`scanner.onUniqueRead` | `let filter = new MultiFrameResultCrossFilter();`
`filter.enableResultDeduplication(EnumCapturedResultItemType.CRIT_BARCODE, true);`
`cvRouter.addResultFilter(filter);`
`let resultReceiver = new Dynamsoft.CVR.CapturedResultReceiver();`
`resultReceiver.onDecodedBarcodesReceived = result => { };`
`cvRouter.addResultReceiver(resultReceiver);` | -| `reader.startScanning()` or
`scanner.show()` | `let cameraView = await Dynamsoft.DCE.CameraView.createInstance();`
`cameraEnhancer = await Dynamsoft.DCE.CameraEnhancer.createInstance(cameraView);`
`//"cameraViewContainer" is usually an HTMLDivElement`
`cameraViewContainer.append(cameraView.getUIElement());`
`cvRouter.setInput(cameraEnhancer);`
`cameraEnhancer.open();`
`cvRouter.startCapturing("SPECIFY-A-TEMPLATE")` | -| `reader.stopScanning()` or
`scanner.hide()` | [cvRouter.stopCapturing()](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/capture-vision-router/multiple-image-processing.html?product=dbr&repoType=web#stopcapturing)
`cameraEnhancer.close();`
`cameraViewContainer.style.display = "none"` | -| `reader.resumeScanning()` | [cvRouter.startCapturing('SPECIFY-A-TEMPLATE')](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/capture-vision-router/multiple-image-processing.html?product=dbr&repoType=web#startcapturing) | - -### Process Settings - -The following assumes `ScanSettings` is the object returned by `reader.getScanSettings()` or `scanner.getScanSettings()` and `SimplifiedCaptureVisionSettings` is returned by `cvRouter.getSimplifiedSettings('SPECIFY-A-TEMPLATE')`. - -| API in v9.x | API in v10.x | -| ------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `reader.getScanSettings()` or
`scanner.getScanSettings()` | No equivalent. | -| `reader.updateScanSettings()` or
`scanner.updateScanSettings()` | No equivalent. | -| `ScanSettings.intervalTime` | [SimplifiedCaptureVisionSettings.minImageCaptureInterval](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/capture-vision-router/interfaces/simplified-capture-vision-settings.html?product=dbr&repoType=web#minimagecaptureinterval) | -| `ScanSettings.duplicateForgetTime` | `let filter = new MultiFrameResultCrossFilter();`
`filter.setDuplicateForgetTime();`
`cvRouter.addResultFilter(filter)` | -| `ScanSettings.whenToPlaySoundforSuccessfulRead` | No equivalent. Use [Dynamsoft.DCE.Feedback.beep()](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/feedback.html#beep) when appropriate. | -| `ScanSettings.soundOnSuccessfullRead` | [Dynamsoft.DCE.Feedback.beepSoundSource](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/feedback.html#beepsoundsource) | -| `ScanSettings.whenToVibrateforSuccessfulRead` | No equivalent. Use [Dynamsoft.DCE.Feedback.vibrate()](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/feedback.html#vibrate) when appropriate. | -| `ScanSettings.vibrateDuration` | [Dynamsoft.DCE.Feedback.vibrateDuration](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/feedback.html#vibrateduration) | -| `ScanSettings.captureAndDecodeInParallel` | Equivalent to setting [SimplifiedCaptureVisionSettings.minImageCaptureInterval](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/capture-vision-router/interfaces/simplified-capture-vision-settings.html?product=dbr&repoType=web#minimagecaptureinterval) to -1 or 0. | -| `ScanSettings.autoZoom` | [cameraEnhancer.enableEnhancedFeatures(EnumEnhancedFeatures.EF_AUTO_ZOOM)](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/camera-control.html#enableenhancedfeatures) | -| `ScanSettings.autoFocus` | [cameraEnhancer.enableEnhancedFeatures(EnumEnhancedFeatures.EF_ENHANCED_FOCUS)](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/camera-control.html#enableenhancedfeatures) | -| `ScanSettings.autoSuggestTip` | No equivalent. | - - -### Algorithm Settings - -| API in v9.x | API in v10.x | -| ----------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `reader.getRuntimeSettings()` or
`scanner.getRuntimeSettings()` | [cvRouter.getSimplifiedSettings('SPECIFY-A-TEMPLATE')](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/capture-vision-router/settings.html#getsimplifiedsettings) | -| `reader.initRuntimeSettingsWithString('SPECIFY-A-TEMPLATE-STRING')` or
`scanner.initRuntimeSettingsWithString('SPECIFY-A-TEMPLATE-STRING')` | [cvRouter.initSettings('SPECIFY-A-TEMPLATE-STRING')](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/capture-vision-router/settings.html#initsettings) | -| `reader.updateRuntimeSettings('SPECIFY-THE-SETTINGS')` or
`scanner.updateRuntimeSettings('SPECIFY-THE-SETTINGS')` | [cvRouter.updateSettings('SPECIFY-A-TEMPLATE', 'SPECIFY-THE-SETTINGS')](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/capture-vision-router/settings.html#updatesettings) | -| `reader.resetRuntimeSettings()` or
`scanner.resetRuntimeSettings()` | [cvRouter.resetSettings()](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/capture-vision-router/settings.html#resetsettings) | -| `reader.outputRuntimeSettingsToString()` or
`scanner.outputRuntimeSettingsToString()` | Use [cvRouter.outputSettings()](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/capture-vision-router/settings.html#outputsettings) which returns an object instead of a string. | - -## Change the APIs for user interface customization - -| API in v9.x | API in v10.x | -| ------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `scanner.getUIElement()` | [cameraView.getUIElement()](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/cameraview.html#getuielement) | -| `scanner.setUIElement()` | [cameraView.setUIElement()](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/cameraview.html#setuielement) | -| `Dynamsoft.DBR.BarcodeScanner.defaultUIElementURL="THE-URL-TO-THE-HTML"` | [Dynamsoft.DCE.CameraView.createInstance("THE-URL-TO-THE-HTML")](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/cameraview.html#createinstance) | -| `scanner.barcodeFillStyle`
`scanner.barcodeStrokeStyle`
`scanner.barcodeLineWidth` | Change the preset style `STYLE_GREEN_STROKE` (ID = 2). | -| `scanner.barcodeFillStyleBeforeVerification`
`scanner.barcodeStrokeStyleBeforeVerification`
`scanner.barcodeLineWidthBeforeVerification` | Change the preset style `STYLE_GREEN_STROKE_TRANSPARENT` (ID = 10). | -| `scanner.regionMaskFillStyle`
`scanner.regionMaskStrokeStyle`
`scanner.regionMaskLineWidth` | [cameraView.setScanRegionMaskStyle()](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/cameraview.html#setscanregionmaskstyle) | -| `scanner.setVideoFit()` | [cameraView.setVideoFit()](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/cameraview.html#setvideofit) | -| `scanner.getVideoFit()` | [cameraView.getVideoFit()](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/cameraview.html#getvideofit) | -| `scanner.ifShowScanRegionMask` | [cameraView.setScanRegionMaskVisible()](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/cameraview.html#setscanregionmaskvisible) | - - -## Change the APIs for camera control - -| API in v9.x | API in v10.x, by the independent `CameraEnhancer` instance | -| ------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `scanner.open()` | [cameraEnhancer.open()](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/camera-control.html#open)
[cvRouter.startCapturing('SPECIFY-A-TEMPLATE')](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/capture-vision-router/multiple-image-processing.html?product=dbr&repoType=web#startcapturing) | -| `scanner.close()` | [cvRouter.stopCapturing()](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/capture-vision-router/multiple-image-processing.html?product=dbr&repoType=web#stopcapturing)
[cameraEnhancer.close()](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/camera-control.html#close) | -| `scanner.isOpen()` | [cameraEnhancer.isOpen()](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/camera-control.html#isopen) | -| `scanner.singleFrameMode` | [cameraEnhancer.singleFrameMode](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/acquisition.html#singleframemode) | -| `scanner.ifSkipCameraInspection` | [cameraEnhancer.ifSkipCameraInspection](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/camera-control.html#ifskipcamerainspection) | -| `scanner.ifSaveLastUsedCamera` | [cameraEnhancer.ifSaveLastUsedCamera](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/camera-control.html#ifsavelastusedcamera) | -| `scanner.getAllCameras()` | [cameraEnhancer.getAllCameras()](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/camera-control.html#getallcameras) | -| `scanner.getCurrentCamera()` | [cameraEnhancer.getSelectedCamera()](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/camera-control.html#getselectedcamera) | -| `scanner.setCurrentCamera()` | [cameraEnhancer.selectCamera()](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/camera-control.html#selectcamera) | -| `scanner.getResolution()` | [cameraEnhancer.getResolution()](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/camera-control.html#getresolution) | -| `scanner.setResolution()` | [cameraEnhancer.setResolution()](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/camera-control.html#setresolution) | -| `scanner.getVideoSettings()` | [cameraEnhancer.getVideoSettings()](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/camera-control.html#getvideosettings) | -| `scanner.updateVideoSettings()` | [cameraEnhancer.updateVideoSettings](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/camera-control.html#updatevideosettings) | -| `Dynamsoft.DBR.Barcodescanner.testCameraAccess()` | [Dynamsoft.DCE.CameraEnhancer.testCameraAccess()](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/camera-control.html#testcameraaccess) | -| `scanner.play()` | [cameraEnhancer.open()](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/camera-control.html#open) or
[cameraEnhancer.resume()](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/camera-control.html#resume) if paused. | -| `scanner.onPlayed` | [cameraEnhancer.on("played", fn)](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/auxiliary.html#on) | -| `scanner.pauseScan()` | [cvRouter.stopCapturing()](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/capture-vision-router/multiple-image-processing.html?product=dbr&repoType=web#stopcapturing) while camera is still playing. | -| `scanner.resumeScan()` | [cvRouter.startCapturing('SPECIFY-A-TEMPLATE')](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/capture-vision-router/multiple-image-processing.html?product=dbr&repoType=web#startcapturing) when camera is already playing. | -| `scanner.pause()` | [cameraEnhancer.pause()](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/camera-control.html#pause) | -| `scanner.stop()` | [cameraEnhancer.close()](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/camera-control.html#close) | -| `scanner.videoSrc` | [cameraEnhancer.videoSrc](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/camera-control.html#videosrc) | -| `scanner.getCapabilities()` | [cameraEnhancer.getCapabilities()](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/camera-control.html#getcapabilities) | -| `scanner.getCameraSettings()` | [cameraEnhancer.getCameraSettings()](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/camera-control.html#getcamerasettings) | -| `scanner.getFrameRate()` | [cameraEnhancer.getFrameRate()](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/camera-control.html#getframerate) | -| `scanner.setFrameRate()` | [cameraEnhancer.setFrameRate()](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/camera-control.html#setframerate) | -| `scanner.turnOnTorch()` | [cameraEnhancer.turnOnTorch()](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/camera-control.html#turnontorch) | -| `scanner.turnOffTorch()` | [cameraEnhancer.turnOffTorch()](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/camera-control.html#turnofftorch) | -| `scanner.getZoomSettings()` | [cameraEnhancer.getZoomSettings()](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/camera-control.html#getzoomsettings) | -| `scanner.setZoom()` | [cameraEnhancer.setZoom()](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/camera-control.html#setzoom) | -| `scanner.resetZoom()` | [cameraEnhancer.resetZoom()](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/camera-control.html#resetzoom) | -| `scanner.getFocusSettings()` | [cameraEnhancer.getFocusSettings()](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/camera-control.html#getfocussettings) | -| `scanner.setFocus()` | [cameraEnhancer.setFocus()](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/camera-control.html#setfocus) | -| `scanner.enableTapToFocus()` | [cameraEnhancer.enableEnhancedFeatures(EnumEnhancedFeatures.EF_TAP_TO_FOCUS)](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/camera-control.html#enableenhancedfeatures) | -| `scanner.disableTapToFocus()` | [cameraEnhancer.disableEnhancedFeatures(EnumEnhancedFeatures.EF_TAP_TO_FOCUS)](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/camera-control.html#disableenhancedfeatures) | -| `scanner.isTapToFocusEnabled()` | No equivalent. | -| `scanner.getColorTemperature()` | [cameraEnhancer.getColorTemperature()](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/camera-control.html#getcolortemperature) | -| `scanner.setColorTemperature()` | [cameraEnhancer.setColorTemperature()](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/camera-control.html#setcolortemperature) | -| `scanner.getExposureCompensation()` | [cameraEnhancer.getExposureCompensation()](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/camera-control.html#getexposurecompensation) | -| `scanner.setExposureCompensation()` | [cameraEnhancer.setExposureCompensation()](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/camera-control.html#setexposurecompensation) | - -## API Changes for RuntimeSettings and Templates - -Previously, in v9.x of DBR JS, there were several ways to change the settings of the `BarcodeReader` or `BarcodeScanner` instance. The first and most popular was to use the RuntimeSettings interface, and the second was to use JSON Templates. In this section of the upgrade guide, we will detail the API changes that have been made to these two configurations. - -### Migrate Your Templates - -The template system is upgraded. The template you used for the previous version can't be directly recognized by the new version. Please download the TemplateConverter tool (only Windows) or contact us to upgrade your template. - -Once you have the new template, please use the new template-based API as follows: - -| Old APIs | New APIs | -| :----------- | :------- | -| `reader.initRuntimeSettingsWithString()` | [cvRouter.initSettings()](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/capture-vision-router/settings.html?product=dbr&lang=javascript#initsettings) | -| `reader.outputRuntimeSettingsToString()` | [cvRouter.outputSettings()](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/capture-vision-router/settings.html?product=dbr&lang=javascript#outputsettings) | - - -> Note: -> Like v9.x, the JavaScript edition of the Barcode Reader only allows for JSON strings to be used as templates. JSON files cannot be used to initiate the settings in the JavaScript edition. - -### Changes to the RuntimeSettings - -The second way in which the settings can be defined in v9.x was to use the `RuntimeSettings` interface. In v10.x, the `RuntimeSettings` have been refactored. It retains commonly used properties while removing the previously complex property settings, which are now exclusively supported through templates. The APIs for accessing and updating `RuntimeSettings` has been adjusted as follows: - -| Old APIs | New APIs | -| :----------- | :------- | -| `scanner.getRuntimeSettings()` | [cvRouter.getSimplifiedSettings()](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/capture-vision-router/settings.html?product=dbr&lang=javascript#getsimplifiedsettings) | -| `scanner.updateRuntimeSettings()` | [cvRouter.updateSettings()](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/capture-vision-router/settings.html?product=dbr&lang=javascript#updatesettings) | - -#### Migrate to SimplifiedCaptureVisionSettings - -The following properties are replaced by similar properties under `SimplifiedCaptureVisionSettings`. They can also be set via a template string. These properties, compared to the ones in `SimplifiedBarcodeReaderSettings` that are in the next section, are shared across all of the Capture Vision products, so they are not specific to just the Barcode Reader. - -| RuntimeSettings Property | SimplifiedCaptureVisionSettings Parameter | Template File Parameter | -| ------------------------------- | ----------------------------------------- | ----------------------- | -| `region` | [`roi`](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/capture-vision-router/interfaces/simplified-capture-vision-settings.html#roi) & [`roiMeasuredInPercentage`](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/capture-vision-router/interfaces/simplified-capture-vision-settings.html#roimeasuredinpercentage) | [`TargetROIDef.Location.Offset`]({{ site.dcv_parameters }}target-roi-def/location.html?product=dbr&repoType=core) | -| `timeout` | **Deprecated and no longer available** | **Deprecated and no longer available** | - -#### Migrate to SimplifiedBarcodeReaderSettings - -The following properties are replaced by similar properties under `SimplifiedBarcodeReaderSettings`. The majority of them can also be set via a template file(String). - -| RuntimeSettings Property | SimplifiedBarcodeReaderSettings Property | Template File Parameter | -| ------------------------------- | ----------------------------------------- | ----------------------- | -| `minBarcodeTextLength` | [`minBarcodeTextLength`](../api-reference/interfaces/simplified-barcode-reader-settings.md#minbarcodetextlength) | [`BarcodeFormatSpecification.BarcodeTextLengthRangeArray`]({{ site.dcv_parameters }}barcode-format-specification/barcode-text-length-range-array.html?product=dbr&repoType=core) | -| `minResultConfidence` | [`minResultConfidence`](../api-reference/interfaces/simplified-barcode-reader-settings.md#minresultconfidence) | [`BarcodeFormatSpecification.MinResultConfidence`]({{ site.dcv_parameters }}barcode-format-specification/min-result-confidence.html?product=dbr&repoType=core) | -| `localizationModes` | [`localizationModes`](../api-reference/interfaces/simplified-barcode-reader-settings.md#localizationmodes) | [`BarcodeReaderTaskSetting.LocationModes`]({{ site.dcv_parameters }}barcode-reader-task-settings/localization-modes.html?product=dbr&repoType=core) | -| `expectedBarcodesCount` | [`expectedBarcodesCount`](../api-reference/interfaces/simplified-barcode-reader-settings.md#expectedbarcodescount) | [`BarcodeReaderTaskSetting.ExpectedBarcodesCount`]({{ site.dcv_parameters }}barcode-reader-task-settings/expected-barcodes-count.html?product=dbr&repoType=core) | -| `barcodeFormatIds` | [`barcodeFormatIds`](../api-reference/interfaces/simplified-barcode-reader-settings.md#barcodeformatids) | [`BarcodeReaderTaskSetting.BarcodeFormatIds`]({{ site.dcv_parameters }}barcode-reader-task-settings/barcode-format-ids.html?product=dbr&repoType=core) | -| `barcodeFormatIds_2` | [`barcodeFormatIds`](../api-reference/interfaces/simplified-barcode-reader-settings.md#barcodeformatids) | [`BarcodeReaderTaskSetting.BarcodeFormatIds`]({{ site.dcv_parameters }}barcode-reader-task-settings/barcode-format-ids.html?product=dbr&repoType=core) | -| `deblurModes` | [`deblurModes`](../api-reference/interfaces/simplified-barcode-reader-settings.md#deblurmodes) | [`BarcodeReaderTaskSetting.DeblurModes`]({{ site.dcv_parameters }}barcode-reader-task-settings/deblur-modes.html?product=dbr&repoType=core) | -| `deblurLevel` | [`deblurModes`](../api-reference/interfaces/simplified-barcode-reader-settings.md#deblurmodes) | [`BarcodeReaderTaskSetting.DeblurModes`]({{ site.dcv_parameters }}barcode-reader-task-settings/deblur-modes.html?product=dbr&repoType=core) | -| `maxAlgorithmThreadCount` | [`maxThreadsInOneTask`]({{ site.dbr_cpp_api }}simplified-barcode-reader-settings.html#maxthreadsinonetask) | [`BarcodeReaderTaskSetting.MaxThreadsInOneTask`]({{ site.dcv_parameters }}barcode-reader-task-settings/max-threads-in-one-task.html?product=dbr&repoType=core) | - -> Remarks: -> -> * The 2 groups of barcode formats are merged. -> * `DeblurLevel` is deprecated. You can use `DeblurModes` instead. - -| FurtherModes Property | SimplifiedBarcodeReaderSettings Property | Template File Parameter | -| ---------------------- | ----------------------------------------- | ----------------------- | -| `grayscaleTransformationModes` | [`grayscaleTransformationModes`](../api-reference/interfaces/simplified-barcode-reader-settings.md#grayscaletransformationmodes) | [`ImageParameter.GrayscaleTransformationModes`]({{ site.dcv_parameters }}image-parameter/grayscale-enhancement-modes.html?product=dbr&repoType=core) | -| `imagePreprocessingModes` | [`grayscaleEnhancementModes`](../api-reference/interfaces/simplified-barcode-reader-settings.md#grayscaleenhancementmodes) | [`ImageParameter.GrayscaleEnhancementModes`]({{ site.dcv_parameters }}image-parameter/grayscale-transformation-modes.html?product=dbr&repoType=core) | - -> Remarks: The mode `IPM_MORPHOLOGY` of `imagePreprocessingModes` is migrated to `BinarizationModes`. The mode arguments `MorphOperation`, `MorphOperationKernelSizeX`, `MorphOperationKernelSizeY`, `MorphShape` are now available for all modes of `BinarizationModes`. - -#### Migrate to Template - -So far, we mentioned the settings that have been included in the *SimplifiedCaptureVisionSettings* and the *SimplifiedBarcodeReaderSettings*. However, not all of the `RuntimeSettings` were moved to either of these interfaces. Some settings have to be defined via a template. Here is a list of all the settings and their corresponding Template File Parameter: - -| RuntimeSettings Property | Template File Parameter | -| ------------------------------- | ----------------------- | -| `scaleDownThreshold` | [`ImageParameter.ScaleDownThreshold`]({{ site.dcv_parameters }}image-parameter/scale-down-threshold.html?product=dbr&repoType=core) | -| `binarizationModes` | [`ImageParameter.BinarizationModes`]({{ site.dcv_parameters }}image-parameter/binarization-modes.html?product=dbr&repoType=core) | -| `textResultOrderModes` | [`BarcodeReaderTaskSetting.TextResultOrderModes`]({{ site.dcv_parameters }}barcode-reader-task-settings/text-result-order-modes.html?product=dbr&repoType=core) | -| `returnBarcodeZoneClarity` | [`BarcodeReaderTaskSetting.ReturnBarcodeZoneClarity`]({{ site.dcv_parameters }}barcode-reader-task-settings/return-barcode-zone-clarity.html?product=dbr&repoType=core) | -| `scaleUpModes` | [`ImageParameter.ScaleUpModes`]({{ site.dcv_parameters }}image-parameter/scale-up-modes.html?product=dbr&repoType=core) | -| `barcodeZoneMinDistanceToImageBorders` | [`BarcodeFormatSpecification.BarcodeZoneMinDistanceToImageBorders`]({{ site.dcv_parameters }}barcode-format-specification/barcode-zone-min-distance-to-image-borders.html?product=dbr&repoType=core) | -| `terminatePhase` | [`BarcodeReaderTaskSetting.TerminateSettings`]({{ site.dcv_parameters }}barcode-reader-task-settings/terminate-setting.html?product=dbr&repoType=core) | - -| FurtherModes Property | Template File Parameter | -| ---------------------- | ----------------------- | -| `colourConversionModes` | [`ImageParameter.ColourConversionModes`]({{ site.dcv_parameters }}image-parameter/colour-conversion-modes.html?product=dbr&repoType=core) | -| `regionPredetectionModes` | [`ImageParameter.RegionPredetectionModes`]({{ site.dcv_parameters }}image-parameter/region-predetection-modes.html?product=dbr&repoType=core) | -| `textureDetectionModes` | [`ImageParameter.TextureDetectionModes`]({{ site.dcv_parameters }}image-parameter/texture-detection-modes.html?product=dbr&repoType=core) | -| `textFilterModes` | [`ImageParameter.TextDetectionMode`]({{ site.dcv_parameters }}image-parameter/text-detection-mode.html?product=dbr&repoType=core) & [`ImageParameter.IfEraseTextZone`]({{ site.dcv_parameters }}image-parameter/if-erase-text-zone.html?product=dbr&repoType=core) | -| `dpmCodeReadingModes` | [`BarcodeReaderTaskSetting.DPMCodeReadingModes`]({{ site.dcv_parameters }}barcode-reader-task-settings/dpm-code-reading-modes.html?product=dbr&repoType=core) | -| `deformationResistingModes` | [`BarcodeReaderTaskSetting.DeformationResistingModes`]({{ site.dcv_parameters }}barcode-reader-task-settings/deformation-resisting-modes.html?product=dbr&repoType=core) | -| `barcodeComplementModes` | [`BarcodeReaderTaskSetting.BarcodeComplementModes`]({{ site.dcv_parameters }}barcode-reader-task-settings/barcode-complement-modes.html?product=dbr&repoType=core) | -| `barcodeColourModes` | [`BarcodeReaderTaskSetting.BarcodeColourModes`]({{ site.dcv_parameters }}barcode-reader-task-settings/barcode-colour-modes.html?product=dbr&repoType=core) | - - -## Other API changes - -| API in v9.x | API in v10.x | -| -------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `scanner.convertToPageCoordinates()` | [cameraEnhancer.convertToPageCoordinates()](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/ui.html#converttopagecoordinates) | -| `scanner.convertToClientCoordinates()` | [cameraEnhancer.convertToClientCoordinates()](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/ui.html#converttoclientcoordinates) | -| `scanner.showTip()` | [cameraEnhancer.setTipConfig()](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/cameraview.html#settipconfig)
[cameraEnhancer.setTipVisible(true)](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/cameraview.html#settipvisible) | -| `scanner.hideTip()` | [cameraEnhancer.setTipVisible(false)](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/cameraview.html#settipvisible) | -| `scanner.onTipSuggested()` | No equivalent. | -| `scanner.updateTipMessage()` | [cameraView.updateTipMessage()](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/cameraview.html#updatetipmessage) | -| `reader.getModeArgument()`
`reader.setModeArgument()` | No equivalent. | -| `scanner.ifSaveOriginalImageInACanvas`
`scanner.getOriginalImageInACanvas()` | `settings = cvRouter.getSimplifiedSettings('SPECIFY-A-TEMPLATE');`
`settings.capturedResultItemTypes += Dynamsoft.Core.EnumCapturedResultItemType.CRIT_ORIGINAL_IMAGE;`
`await cvRouter.updateSettings("detect-document-boundaries", settings);`
`const resultReceiver = new Dynamsoft.CVR.CapturedResultReceiver();`
`resultReceiver.onOriginalImageResultReceived = result => { // GET-THE-ORIGINAL-IMAGE //};`
`cvRouter.addResultReceiver(resultReceiver)` | \ No newline at end of file diff --git a/programming/javascript/upgrade-guide/index.md b/programming/javascript/upgrade-guide/index.md deleted file mode 100644 index dc9c8dd7..00000000 --- a/programming/javascript/upgrade-guide/index.md +++ /dev/null @@ -1,15 +0,0 @@ ---- -layout: default-layout -title: Upgrade guide Index - Dynamsoft Barcode Reader JavaScript Edition -description: This is the index page for the upgrade guide articles. -keywords: user guide, upgrade, javascript, js -needAutoGenerateSidebar: true -permalink: /programming/javascript/upgrade-guide/index.html ---- - -# Upgrade Guide - -* [Upgrade from version 9 to 10](./9to10.md) -* [Upgrade from version 8 to 9](./8to9.md) -* [Upgrade from version 7 to 9](./7to9.md) -* [END OF SUPPORT NOTICE for version 7](./7-notice.md) diff --git a/programming/javascript/user-guide/barcode-scanner-customization-v10.5.3000.md b/programming/javascript/user-guide/barcode-scanner-customization-v10.5.3000.md deleted file mode 100644 index 76d62b08..00000000 --- a/programming/javascript/user-guide/barcode-scanner-customization-v10.5.3000.md +++ /dev/null @@ -1,191 +0,0 @@ ---- -layout: default-layout -needAutoGenerateSidebar: true -needGenerateH3Content: true -noTitleIndex: true -title: Customizations - Dynamsoft Barcode Scanner v10.5.3000 JavaScript Edition -keywords: Documentation, Barcode Scanner, Dynamsoft Barcode Scanner JavaScript Edition, customization -description: Dynamsoft Barcode Scanner customization ---- - -# Customize Your BarcodeScanner - -- [Specify the barcode format](#specify-the-barcode-format) -- [Use customized template](#use-customized-template) -- [Config the pre-built UIs](#config-the-pre-built-uis) -- [Use BarcodeScanner in frameworks](#use-barcodescanner-in-frameworks) - -## Specify the barcode format - -Specifying the target barcode formats not only speeds up the recognition process but also improves accuracy. This is one of the most common customization needs. BarcodeScanner provides two ways to specify the barcode formats. For example, if your target formats are `QR_CODE` and `CODE_128`: - -> [!NOTE] -> See [all supported barcode formats](https://officecn.dynamsoft.com:808/barcode-reader/barcode-types/). - -### Option 1: Set via BarcodeScannerConfig - -Add the following configuration in [`BarcodeScannerConfig`]({{ site.js_api }}barcode-scanner.html#barcodescannerconfig): - -```js -const barcodeScanner = new Dynamsoft.BarcodeScanner({ - // ... - barcodeFormats:[Dynamsoft.DBR.EnumBarcodeFormat.BF_QR_CODE , Dynamsoft.DBR.EnumBarcodeFormat.BF_CODE_128], - // ... -}); -``` - -### Option 2: Specify in a template file - -The benefit of this approach is that the template file can be reused across different platforms or programming languages, ensuring performance consistency across scenarios. To do this, follow these steps: - -1. Open `dist\DBR-PresetTemplates.json` in your code editor. This file contains all the preset templates related to barcode reading. - -2. Add the `BarcodeFormatIds` to the `BarcodeReaderTaskSettingOptions` object. - -3. Update `BarcodeFormatIds` as shown below. You can get barcode format strings [here](https://www.dynamsoft.com/capture-vision/docs/core/enums/barcode-reader/barcode-format.html). - -description - -Refer to [`Use customized template`](#use-customized-template) for more details. - -> [!IMPORTANT] -> Due to the powerful customization capabilities, the number of configurable parameters in the templates is extensive and relatively complex. feel free to [contact us](https://www.dynamsoft.com/contact/) if you need help creating a custom template. - -## Use customized template - -In more complex scenarios—such as blurred, damaged, curved, or unevenly lit barcodes—you might need a custom template to perform specific image processing steps. BarcodeScannerConfig provides a property to load a template file, allowing you to customize the algorithm’s processing workflow. - -> [!WARNING] -> This operation will overwrite the built-in templates. - -```js - const barcodeScannerConfig = { - // The path to your custom JSON template that defines the scanning process. - templateFilePath:'path/to/DBR-PresetTemplates.json' - }; - // Initialize the BarcodeScanner with the above BarcodeScannerConfig object - const barcodeScanner = new Dynamsoft.BarcodeScanner(barcodeScannerConfig); -``` - -## Config the Pre-built UIs - -The built-in UI of `BarcodeScanner` is composed of `BarcodeScannerView` and `BarcodeResultView`. By default, regardless of the scanning mode, `BarcodeScanner` only displays the `CameraView` to ensure the essential workflow can proceed. Other UI components can be shown or hidden manually through `barcodeScannerConfig`. Let's break down these two Views: - -### BarcodeScannerView - -The `BarcodeScannerView` is composed of the following UI elements: - -description - -1. **Camera View**: The Camera View is the camera viewfinder UI component within the `BarcodeScannerView`. This viewfinder occupies the majority of the space within the `BarcodeScannerView` to give the user a clear view and precise control of the image being scanned. - -2. **Load Image Button**: This button allows the user to scan a file of a barcode-containing image from the device's local storage. You can decide whether to show or hide the button by [showUploadImageButton]({{ site.js_api }}barcode-scanner.html#barcodescannerconfig) property. - -3. **Close Scanner Button**: This button closes the Barcode Scanner, return a [`BarcodeScanResult`]({{ site.js_api }}barcode-scanner.html#barcodescanresult) object and destroys the **`BarcodeScanner`** instance. You can decide whether to show or hide the button by [showCloseButton]({{ site.js_api }}barcode-scanner.html#scannerviewconfig) property. - -### BarcodeResultView (MULTI_UNIQUE mode only) - -Here is a quick breakdown of the `MULTI_UNIQUE` UI elements of the `BarcodeResultView` view: - -description - -1. **Barcode Results List**: The list used to display the decoding results.The list is updated whenever a new barcode is successfully decoded, or the same code is detected again after a specific [duplicateForgetTime]({{ site.js_api }}barcode-scanner.html#barcodescannerconfig). - -2. **Clear Button**: The button on the bottom left, which clears all elements of the current `Barcode Results List`. You can change the style of the Button with [BarcodeResultViewToolbarButtonsConfig]({{ site.js_api }}barcode-scanner.html#barcoderesultviewtoolbarbuttonsconfig). - -3. **Done Button**: The button on the bottom right, which closes the Barcode Scanner, return a [`BarcodeScanResult`]({{ site.js_api }}barcode-scanner.html#barcodescanresult) object that includes all unique barcodes and destroys the **`BarcodeScanner`** instance. You can change the style of the Button with [BarcodeResultViewToolbarButtonsConfig]({{ site.js_api }}barcode-scanner.html#barcoderesultviewtoolbarbuttonsconfig). - -### Manually modify the UI file - -Another way to fully customize the UI is by directly editing the `.xml` file. In the `dist/` directory, you'll find the `barcode-scanner.ui.xml` file, which is the default UI for the `BarcodeScanner`. You can make a copy of it and apply your own modifications. For example, to double the size of the `UploadImage` icon, you can edit the file like this: - -```xml - -``` - -Once you've made your changes, just set the new `uiPath` in the configuration. If everything is configured correctly, the updated UI will appear the next time you refresh the page. - -```js - const barcodeScanner = new Dynamsoft.BarcodeScanner({ - //... - uiPath: "path/to/new-barcode-scanner.ui.xml?v=", - //... - }); -``` - -## Use BarcodeScanner in frameworks - -Integrating `BarcodeScanner` into frameworks like `Angular`, `React`, and `Vue` is a little different compared to native usage. You can also refer to [the ready-made samples for popular frameworks](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/main/barcode-scanner-api-samples/scan-single-barcode) directly without reading this guide. - -### Installation - -Open the terminal from your project root and install **Dynamsoft Barcode Reader SDK** with the following command: - -```sh -npm install dynamsoft-barcode-reader-bundle@11.0.3000 -E -``` - -### Component for video decoding - -Here’s how to quickly set up a video barcode scanner using the `BarcodeScanner` class: - -```ts - const config = { - license: "YOUR-LICENSE-KEY", // Replace with your license key - } - const barcodeScanner = new BarcodeScanner(config); - barcodeScanner.launch().then((result)=>{ - console.log(result); // Handle the decoding result here - }); -``` - -#### Define the resource paths - -To ensure stability, especially in environments with limited internet access, it’s a good idea to **host all required resources locally** (e.g., under the dist/ folder). -Below is an example using the official CDN — feel free to replace it with your own path: - -```ts - const config = { - license: "YOUR-LICENSE-KEY", - // Configures the paths where the .wasm files and other necessary resources for modules are located. - engineResourcePaths: { - // Using jsDelivr CDN as an example - rootDirectory: "https://cdn.jsdelivr.net/npm/dynamsoft-barcode-reader-bundle@11.0.3000/dist/", - }, - // Path to the UI (.xml template file). - uiPath: "https://cdn.jsdelivr.net/npm/dynamsoft-barcode-reader-bundle@11.0.3000/dist/barcode-scanner.ui.xml", - }; -``` - -#### Set up the video container - -Specify the container where the scanner UI should be rendered: - -```ts - const config = { - container: ".barcode-scanner-view", // CSS selector for the scanner container - }; -``` - -Make sure your HTML includes the corresponding element: - -```html -
-``` - -The above steps cover the key considerations when using the `BarcodeScanner` component within a modern JavaScript framework. To recap: - -- Install the SDK with an exact version to avoid compatibility issues. - -- Define resource paths explicitly — either via CDN or local dist/ folder — to ensure consistent loading behavior. - -- Configure and launch the scanner using the provided component API. - -- Set up a container element to properly display the scanner UI. - -By following these best practices, you'll ensure a stable and reliable integration of `BarcodeScanner` into your application. \ No newline at end of file diff --git a/programming/javascript/user-guide/barcode-scanner-v10.5.3000.md b/programming/javascript/user-guide/barcode-scanner-v10.5.3000.md deleted file mode 100644 index f8449ce7..00000000 --- a/programming/javascript/user-guide/barcode-scanner-v10.5.3000.md +++ /dev/null @@ -1,229 +0,0 @@ ---- -layout: default-layout -needAutoGenerateSidebar: true -needGenerateH3Content: true -noTitleIndex: true -title: User Guide - Dynamsoft Barcode Scanner v10.5.3000 JavaScript Edition -keywords: Documentation, Barcode Scanner, Dynamsoft Barcode Scanner JavaScript Edition, -description: Dynamsoft Barcode Scanner User Guide ---- - -# Build a Web-Based Barcode Scanner Using Just a Few Lines of JavaScript - -This user guide provides a step-by-step walkthrough of a "Hello World" web application using the `BarcodeScanner` JavaScript Edition. - -The `BarcodeScanner` class offers the following features: - -- High-level APIs that deliver core functionality with a single line of code. - -- Pre-built UI components for fast and easy integration. - -- Intuitive configuration objects that streamline both algorithm and UI setup. - -We recommend using this guide as a reference when creating your own application. If you are looking for a fully customizable barcode decoding library, you are welcome to use the [Foundational APIs](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/user-guide/index.html). Before starting, ensure the **basic requirements** are met. - - - -- Internet connection -- A supported browser -- Camera access - -> [!TIP] -> Please refer to [system requirements](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/faq/system-requirement.html) for more details. - -## License - -### Trial License - - - -When getting started with Barcode Scanner, we recommend [getting your own 30-day trial license](https://www.dynamsoft.com/customer/license/trialLicense/?product=dbr&utm_source=guide&package=js) - -{% include trialLicense.html %} - -> [!IMPORTANT] -> The trial license can be renewed via the [customer portal](https://www.dynamsoft.com/customer/license/trialLicense/?product=dbr&utm_source=guide&package=js) twice, each time for another 15 days, giving you a total of 60 days to develop your own application using the solution. Please contact the [Dynamsoft Support Team](https://www.dynamsoft.com/company/contact/) if you need more time for a full evaluation. - -### Full License - -If you are fully satisfied with the solution and would like to move forward with a full license, please contact the [Dynamsoft Sales Team](https://www.dynamsoft.com/company/contact/). - -## Quick Start: Hello World Example - -```html - - - - - - - -``` - -

- - Code in Github - -   - - Run via JSFiddle - -   - - Run in Dynamsoft - -

- -### Step 1: Setting up the HTML and Including the Barcode Scanner - -As outlined earlier, this guide will help you create a simple Hello World barcode scanning application using vanilla JavaScript. The full sample code is also available in the [GitHub repository](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/v10.5.30). - -The first step before writing the code is to include the SDK in your application. You can simply include the SDK by using the precompiled script. - -```html - - - - - - -``` - -In this example, we include the precompiled Barcode Scanner SDK script via public CDN in the header. - -
- -
-
Use a public CDN
- -The simplest way to include the SDK is to use either the [**jsDelivr**](https://jsdelivr.com/) or [**UNPKG**](https://unpkg.com/) CDN. - -- jsDelivr - - ```html - - ``` - -- UNPKG - - ```html - - ``` - -When using a framework such as **React**, **Vue** or **Angular**, we recommend adding the package as a dependency using a package manager such as **npm** or **yarn**: - - ```sh - npm i dynamsoft-barcode-reader-bundle@10.5.3000 - # or - yarn add dynamsoft-barcode-reader-bundle@10.5.3000 - ``` - -As for package managers like **npm** or **yarn**, you likely need to specify the location of the engine files as a link to a CDN. Please see the [BarcodeScannerConfig API](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/barcode-scanner.html#barcodescannerconfig) for a code snippet on how to set the `engineResourcePaths`. -
- -
-
Host the SDK yourself
- -Alternatively, you may choose to download the SDK and host the files on your own server or preferred CDN. This approach provides better control over versioning and availability. - -- From the website - - [Download Dynamsoft Barcode Reader JavaScript Package](https://www.dynamsoft.com/barcode-reader/downloads/?ver=10.5.30&utm_source=guide&product=dbr&package=js) - - The resources are located at path `dynamsoft/distributables/`. - -- From npm - - ```sh - npm i dynamsoft-barcode-reader-bundle@10.5.3000 - ``` - - The resources are located at the path `node_modules/`, without `@`. You can copy it elsewhere and add `@` tag. One more thing to do is to [specify the engineResourcePaths](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/barcode-scanner.html#barcodescannerconfig) so that the SDK can correctly locate the resources. - - > [!IMPORTANT] - > Since "node_modules" is reserved for Node.js dependencies, and in our case the package is used only as static resources, we recommend either renaming the "node_modules" folder or moving the "dynamsoft-" packages to a dedicated folder for static resources in your project to facilitate self-hosting. - -You can typically include SDK like this: - -```html - -``` -
- -
- -Barcode Scanner comes with a **Ready-to-Use UI**. When the Barcode Scanner launches, it creates a container which it populates with the **Ready-to-Use UI**. - -### Step 2: Initializing the Barcode Scanner - -```js -// Initialize the Dynamsoft Barcode Scanner -const barcodescanner = new Dynamsoft.BarcodeScanner({ - // Please don't forget to replace YOUR_LICENSE_KEY_HERE - license: "YOUR_LICENSE_KEY_HERE", -}); -``` - -This is the **simplest** way to initialize the Barcode Scanner. The configuration object must include a valid **license** key. Without it, the scanner will fail to launch and display an error. For help obtaining a license, see the [licensing](#license) section. - -> [!TIP] -> By default, the `BarcodeScanner` scans a single barcode at a time. However, it also supports a `MULTI_UNIQUE` scanning mode, which continuously scans and accumulates unique results in real time. You can enable this mode by modifying the [`BarcodeScannerConfig`](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/barcode-scanner.html#barcodescannerconfig) as follows: - -```js -// Initialize the Dynamsoft Barcode Scanner in MULTI_UNIQUE mode -const barcodescanner = new Dynamsoft.BarcodeScanner({ - license: "YOUR_LICENSE_KEY_HERE", - scanMode: Dynamsoft.EnumScanMode.SM_MULTI_UNIQUE, - showResultView: true, -}); -``` - -### Step 3: Launching the Barcode Scanner - -```js -(async () => { - // Launch the scanner and wait for the result - const result = await barcodescanner.launch(); - alert(result.barcodeResults[0].text); -})(); -``` - -Now that the Barcode Scanner has been initialized and configured, it is ready to be launched! Upon launch, the Barcode Scanner presents the main **`BarcodeScannerView`** UI in its container on the page, and is ready to start scanning. By default, we use the `SINGLE` scanning mode, which means only one decoding result will be included in the final result. In the code above, we directly alerted the successfully decoded barcode text on the page. - -> [!NOTE] -> In the Hello World sample, after a successfully decoding process, the scanner closes and the user is met with an empty page. In order to open the scanner again, the user must refresh the page. You may choose to implement a more user-friendly behavior in a production environment, such as presenting the user with an option to re-open the Barcode Scanner upon closing it. - -## Next Steps - -Now that you've implemented the basic functionality, here are some recommended next steps to further explore the capabilities of the Barcode Scanner - -1. Learn how to [Customize the Barcode Scanner](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/user-guide/barcode-scanner-customization.html) -2. Check out the [Official Samples and Demo](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/index.html?ver=10.5.3000) -3. Learn about the [APIs of BarcodeScanner](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/barcode-scanner.html?ver=10.5.3000) diff --git a/programming/javascript/user-guide/barcode-scanner-v11.0.3000.md b/programming/javascript/user-guide/barcode-scanner-v11.0.3000.md deleted file mode 100644 index b6e4977b..00000000 --- a/programming/javascript/user-guide/barcode-scanner-v11.0.3000.md +++ /dev/null @@ -1,230 +0,0 @@ ---- -layout: default-layout -needAutoGenerateSidebar: true -needGenerateH3Content: true -noTitleIndex: true -title: User Guide - Dynamsoft Barcode Scanner v11.0.3000 JavaScript Edition -keywords: Documentation, Barcode Scanner, Dynamsoft Barcode Scanner JavaScript Edition, -description: Dynamsoft Barcode Scanner User Guide ---- - -# Build a Web-Based Barcode Scanner Using Just a Few Lines of JavaScript - -This user guide provides a step-by-step walkthrough of a "Hello World" web application using the `BarcodeScanner` JavaScript Edition. - -The `BarcodeScanner` class offers the following features: - -- High-level APIs that deliver core functionality with a single line of code. - -- Pre-built UI components for fast and easy integration. - -- Intuitive configuration objects that streamline both algorithm and UI setup. - -We recommend using this guide as a reference when creating your own application. If you are looking for a fully customizable barcode decoding library, you are welcome to use the [Foundational APIs](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/user-guide/index.html). Before starting, ensure the **basic requirements** are met. - - - -- Internet connection -- A supported browser -- Camera access - -> [!TIP] -> Please refer to [system requirements](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/faq/system-requirement.html) for more details. - -## License - -When getting started with Barcode Scanner, we recommend getting your own 30-day trial license. - - - -{% include trialLicense.html %} - - - -## Quick Start: Hello World Example - -```html - - - - - - - -``` - -

- - Code in Github - -   - - Run via JSFiddle - -   - - Run in Dynamsoft - -

- -### Step 1: Setting up the HTML and Including the Barcode Scanner - -As outlined earlier, this guide will help you create a simple Hello World barcode scanning application using vanilla JavaScript. The full sample code is also available in the [GitHub repository](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/v11.0.30). - -The first step before writing the code is to include the SDK in your application. You can simply include the SDK by using the precompiled script. - -```html - - - - - - -``` - -In this example, we include the precompiled Barcode Scanner SDK script via public CDN in the header. - -
- -
-
Use a public CDN
- -The simplest way to include the SDK is to use either the [**jsDelivr**](https://jsdelivr.com/) or [**UNPKG**](https://unpkg.com/) CDN. - -- jsDelivr - - ```html - - ``` - -- UNPKG - - ```html - - ``` - -When using a framework such as **React**, **Vue** or **Angular**, we recommend adding the package as a dependency using a package manager such as **npm** or **yarn**: - - ```sh - npm i dynamsoft-barcode-reader-bundle@11.0.3000 - # or - yarn add dynamsoft-barcode-reader-bundle@11.0.3000 - ``` - -As for package managers like **npm** or **yarn**, you likely need to specify the location of the engine files as a link to a CDN. Please see the [BarcodeScannerConfig API](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/barcode-scanner.html#barcodescannerconfig) for a code snippet on how to set the `engineResourcePaths`. -
- -
-
Host the SDK yourself
- -Alternatively, you may choose to download the SDK and host the files on your own server or preferred CDN. This approach provides better control over versioning and availability. - -- From the website - - [Download Dynamsoft Barcode Reader JavaScript Package](https://www.dynamsoft.com/barcode-reader/downloads/?ver=11.0.30&utm_source=guide&product=dbr&package=js) - - The resources are located in the `./dist/` directory. - -- From npm - - ```sh - npm i dynamsoft-barcode-reader-bundle@11.0.3000 - ``` - - The resources are located at the path `node_modules/`, without `@`. You can copy it elsewhere and add `@` tag. - - > [!IMPORTANT] - > Since "node_modules" is reserved for Node.js dependencies, and in our case the package is used only as static resources, we recommend either renaming the "node_modules" folder or moving the "dynamsoft-" packages to a dedicated folder for static resources in your project to facilitate self-hosting. - -You can typically include SDK like this: - -```html - -``` -
- -
- -Barcode Scanner comes with a **Ready-to-Use UI**. When the Barcode Scanner launches, it creates a container which it populates with the **Ready-to-Use UI**. - -### Step 2: Initializing the Barcode Scanner - -```js -// Initialize the Dynamsoft Barcode Scanner -const barcodescanner = new Dynamsoft.BarcodeScanner({ - // Please don't forget to replace YOUR_LICENSE_KEY_HERE - license: "YOUR_LICENSE_KEY_HERE", -}); -``` - -This is the **simplest** way to initialize the Barcode Scanner. The configuration object must include a valid **license** key. Without it, the scanner will fail to launch and display an error. For help obtaining a license, see the [licensing](#license) section. - -> [!TIP] -> By default, the `BarcodeScanner` scans a single barcode at a time. However, it also supports a `MULTI_UNIQUE` scanning mode, which continuously scans and accumulates unique results in real time. You can enable this mode by modifying the [`BarcodeScannerConfig`](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/barcode-scanner.html#barcodescannerconfig) as follows: - -```js -// Initialize the Dynamsoft Barcode Scanner in MULTI_UNIQUE mode -const barcodescanner = new Dynamsoft.BarcodeScanner({ - license: "YOUR_LICENSE_KEY_HERE", - scanMode: Dynamsoft.EnumScanMode.SM_MULTI_UNIQUE, -}); -``` - -### Step 3: Launching the Barcode Scanner - -```js -(async () => { - // Launch the scanner and wait for the result - const result = await barcodescanner.launch(); - // Display the first detected barcode's text in an alert - if (result.barcodeResults.length) { - alert(result.barcodeResults[0].text); - } -})(); -``` - -Now that the Barcode Scanner has been initialized and configured, it is ready to be launched! Upon launch, the Barcode Scanner presents the main **`BarcodeScannerView`** UI in its container on the page, and is ready to start scanning. By default, we use the `SINGLE` scanning mode, which means only one decoding result will be included in the final result. In the code above, we directly alerted the successfully decoded barcode text on the page. - -> [!NOTE] -> In the Hello World sample, after a successfully decoding process, the scanner closes and the user is met with an empty page. In order to open the scanner again, the user must refresh the page. You may choose to implement a more user-friendly behavior in a production environment, such as presenting the user with an option to re-open the Barcode Scanner upon closing it. - -## Next Steps - -Now that you've implemented the basic functionality, here are some recommended next steps to further explore the capabilities of the Barcode Scanner - -1. Learn how to [Customize the Barcode Scanner](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/user-guide/barcode-scanner-customization.html) -2. Check out the [Official Samples and Demo](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/index.html?ver=11.0.3000) -3. Learn about the [APIs of BarcodeScanner](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/barcode-scanner.html?ver=11.0.3000) diff --git a/programming/javascript/user-guide/index-v10.0.20.md b/programming/javascript/user-guide/index-v10.0.20.md deleted file mode 100644 index d7379677..00000000 --- a/programming/javascript/user-guide/index-v10.0.20.md +++ /dev/null @@ -1,766 +0,0 @@ ---- -layout: default-layout -title: v10.0.20 User Guide - Dynamsoft Barcode Reader JavaScript Edition -description: This is the user guide of Dynamsoft Barcode Reader JavaScript SDK. -keywords: user guide, javascript, js -breadcrumbText: User Guide -noTitleIndex: true -needGenerateH3Content: true -needAutoGenerateSidebar: true -permalink: /programming/javascript/user-guide/index-v10.0.20.html -schema: schemas/dynamsoft-facilitates-mit-research-schema.json ---- - - - -# Barcode Reader for Your Website - User Guide - -[Dynamsoft Barcode Reader JavaScript Edition](https://www.dynamsoft.com/barcode-reader/sdk-javascript/) (DBR-JS) is equipped with industry-leading algorithms for exceptional speed, accuracy and read rates in barcode reading. Using its well-designed API, you can turn your web page into a barcode scanner with just a few lines of code. - -![version](https://img.shields.io/npm/v/dynamsoft-barcode-reader.svg) -![downloads](https://img.shields.io/npm/dm/dynamsoft-barcode-reader.svg) -![jsdelivr](https://img.shields.io/jsdelivr/npm/hm/dynamsoft-barcode-reader.svg) -![vulnerabilities](https://img.shields.io/snyk/vulnerabilities/npm/dynamsoft-barcode-reader.svg) - -Once the DBR-JS SDK gets integrated into your web page, your users can access a camera via the browser and read barcodes directly from its video input. - -In this guide, you will learn step by step on how to integrate the DBR-JS SDK into your website. - -Table of Contents - -- [Barcode Reader for Your Website - User Guide](#barcode-reader-for-your-website---user-guide) - - [Hello World - Simplest Implementation](#hello-world---simplest-implementation) - - [Understand the code](#understand-the-code) - - [About the code](#about-the-code) - - [Run the example](#run-the-example) - - [Building your own page](#building-your-own-page) - - [Include the SDK](#include-the-sdk) - - [Use a public CDN](#use-a-public-cdn) - - [Host the SDK yourself](#host-the-sdk-yourself) - - [Prepare the SDK](#prepare-the-sdk) - - [Specify the license](#specify-the-license) - - [Specify the location of the "engine" files (optional)](#specify-the-location-of-the-engine-files-optional) - - [Set up and start image processing](#set-up-and-start-image-processing) - - [Preload the module](#preload-the-module) - - [Create a CaptureVisionRouter object](#create-a-capturevisionrouter-object) - - [Connect an image source](#connect-an-image-source) - - [Register a result receiver](#register-a-result-receiver) - - [Start the process](#start-the-process) - - [Customize the process](#customize-the-process) - - [Adjust the preset template settings](#adjust-the-preset-template-settings) - - [Change barcode settings](#change-barcode-settings) - - [Retrieve the original image](#retrieve-the-original-image) - - [Change reading frequency to save power](#change-reading-frequency-to-save-power) - - [Specify a scan region](#specify-a-scan-region) - - [Edit the preset templates directly](#edit-the-preset-templates-directly) - - [Filter the results (Important)](#filter-the-results-important) - - [Option 1: Verify results across multiple frames](#option-1-verify-results-across-multiple-frames) - - [Option 2: Eliminate redundant results detected within a short time frame](#option-2-eliminate-redundant-results-detected-within-a-short-time-frame) - - [Add feedback](#add-feedback) - - [Customize the UI](#customize-the-ui) - - [API Documentation](#api-documentation) - - [System Requirements](#system-requirements) - - [How to Upgrade](#how-to-upgrade) - - [Release Notes](#release-notes) - - [Next Steps](#next-steps) - -**Popular Examples** - -- Hello World - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v10.0.20/hello-world/hello-world.html) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/hello-world/hello-world.html?ver=10.0.20&utm_source=guide) -- Angular App - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v10.0.20/hello-world/angular) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/hello-world/angular/dist/angular/?ver=10.0.20&utm_source=guide) -- React App - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v10.0.20/hello-world/react) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/hello-world/react/build/?ver=10.0.20&utm_source=guide) -- Vue App - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v10.0.20/hello-world/vue) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/hello-world/vue/dist/?ver=10.0.20&utm_source=guide) -- PWA App - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v10.0.20/hello-world/pwa) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/hello-world/pwa/helloworld-pwa.html?ver=10.0.20&utm_source=guide) -- WebView in Android and iOS - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/v10.0.20/hello-world/webview) -- Read Driver Licenses - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v10.0.20/use-case/read-a-drivers-license.html) \| [Run](https://demo.dynamsoft.com/samples/dbr/js/use-case/read-a-drivers-license.html?ver=10.0.20&utm_source=guide) -- Fill A Form - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v10.0.20/use-case/fill-a-form-with-barcode-reading.html) \| [Run](https://demo.dynamsoft.com/samples/dbr/js/use-case/fill-a-form-with-barcode-reading.html?ver=10.0.20&utm_source=guide) -- Show result information on the video - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v10.0.20/use-case/show-result-texts-on-the-video.html) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/use-case/show-result-texts-on-the-video.html?ver=10.0.20&utm_source=guide) -- Debug Camera and Collect Video Frame - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v10.0.20/others/debug) - -You can also: - -- Try the Official Demo - [Run](https://demo.dynamsoft.com/barcode-reader-js/?ver=10.0.20&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-demo/) -- Try Online Examples - [Run](https://demo.dynamsoft.com/Samples/DBR/JS/index.html?ver=10.0.20&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/v10.0.20/) - -## Hello World - Simplest Implementation - -Let's start with the "Hello World" example of the DBR-JS SDK which demonstrates how to use the minimum code to enable a web page to read barcodes from a live video stream. - -**Basic Requirements** - - Internet connection - - [A supported browser](#system-requirements) - - Camera access - -### Understand the code - -The complete code of the "Hello World" example is shown below - -```html - - - - - - - - - -
- - - - -``` - - - -

- - Code in Github - -   - - Run via JSFiddle - -   - - Run in Dynamsoft - -

- ------ - -#### About the code - -- `Dynamsoft.License.LicenseManager.initLicense()`: This method initializes the license for using the SDK in the application. Note that the string "**DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9**" used in this example points to an online license that requires a network connection to work. Read more on [Specify the license](#specify-the-license). - -- `Dynamsoft.CVR.CaptureVisionRouter.createInstance()`: This method creates a `CaptureVisionRouter` object `cvRouter` which controls the entire process in three steps: - - **Retrieve Images from the Image Source** - - `cvRouter` connects to the image source through the [ImageSourceAdapter](https://www.dynamsoft.com/capture-vision/docs/core/architecture/input.html#image-source-adapter?lang=js) interface with the method `setInput()`. - ```js - cvRouter.setInput(cameraEnhancer); - ``` - > The image source in our case is a [CameraEnhancer](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/user-guide/index.html) object created with `Dynamsoft.DCE.CameraEnhancer.createInstance(cameraView)` - - **Coordinate Image-Processing Tasks** - - The coordination happens behind the scenes. `cvRouter` starts the process by specifying a preset template "ReadSingleBarcode" in the method `startCapturing()`. - ```js - cvRouter.startCapturing("ReadSingleBarcode"); - ``` - - **Dispatch Results to Listening Objects** - - The processing results are returned through the [CapturedResultReceiver](https://www.dynamsoft.com/capture-vision/docs/core/architecture/output.html#captured-result-receiver?lang=js) interface. The `CapturedResultReceiver` object is registered to `cvRouter` via the method `addResultReceiver()`. For more information, please check out [Register a result receiver](#register-a-result-receiver). - ```js - cvRouter.addResultReceiver({/*The-CapturedResultReceiver-Object"*/}); - ``` - - Also note that reading from video is extremely fast and there could be many duplicate results. We can use a [filter](#filter-the-results-important) with result deduplication enabled to filter out the duplicate results. The object is registered to `cvRouter` via the method `addResultFilter()`. - ```js - cvRouter.addResultFilter(filter); - ``` - -> Read more on [Capture Vision Router](https://www.dynamsoft.com/capture-vision/docs/core/architecture/#capture-vision-router). - -### Run the example - -You can run the example deployed to [the Dynamsoft Demo Server](https://demo.dynamsoft.com/Samples/DBR/JS/hello-world/hello-world.html?ver=10.0.20&utm_source=guide) or test it with [JSFiddle code editor](https://jsfiddle.net/DynamsoftTeam/pL4e7yrd/). - -You will be asked to allow access to your camera, after which the video will be displayed on the page. After that, you can point the camera at a barcode to read it. - -When a barcode is decoded, you will see the result text show up under the video and the barcode location will be highlighted in the video feed. - -Alternatively, you can test locally by copying and pasting the code shown above into a local file (e.g. "hello-world.html") and opening it in your browser. - -*Note*: - -If you open the web page as `file:///` or `http://` , the camera may not work correctly because the [MediaDevices: getUserMedia()](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia) method only works in secure contexts (HTTPS), in some or all supporting browsers. - -To make sure your web application can access the camera, please configure your web server to support HTTPS. The following links may help. - -1. NGINX: [Configuring HTTPS servers](https://nginx.org/en/docs/http/configuring_https_servers.html) -2. IIS: [How to create a Self Signed Certificate in IIS](https://aboutssl.org/how-to-create-a-self-signed-certificate-in-iis/) -3. Tomcat: [Setting Up SSL on Tomcat in 5 minutes](https://dzone.com/articles/setting-ssl-tomcat-5-minutes) -4. Node.js: [npm tls](https://nodejs.org/docs/v0.4.1/api/tls.html) - -If the test doesn't go as expected, you can [contact us](https://www.dynamsoft.com/company/contact/?ver=10.0.20&utm_source=guide&product=dbr&package=js). - -## Building your own page - -### Include the SDK - -To utilize the SDK, the initial step involves including the corresponding resource files: - -* `core.js` encompasses common classes, interfaces, and enumerations that are shared across all Dynamsoft SDKs. -* `license.js` introduces the `LicenseManager` class, which manages the licensing for all Dynamsoft SDKs. -* `utility.js` encompasses auxiliary classes that are shared among all Dynamsoft SDKs. -* `dbr.js` defines interfaces and enumerations specifically tailored to the barcode reader module. -* `cvr.js` introduces the `CaptureVisionRouter` class, which governs the entire image processing workflow. -* `dce.js` comprises classes that offer camera support and basic user interface functionalities. - -#### Use a public CDN - -The simplest way to include the SDK is to use either the [jsDelivr](https://jsdelivr.com/) or [UNPKG](https://unpkg.com/) CDN. The "hello world" example above uses **jsDelivr**. - -- jsDelivr - - ```html - - - - - - - ``` - -- UNPKG - - ```html - - - - - - - ``` - -In some rare cases (such as some restricted areas), you might not be able to access the CDN. If this happens, you can use the following files for the test. - -- https://download2.dynamsoft.com/packages/dynamsoft-core@3.0.32/dist/core.js -- https://download2.dynamsoft.com/packages/dynamsoft-license@3.0.20/dist/license.js -- https://download2.dynamsoft.com/packages/dynamsoft-utility@1.0.21/dist/utility.js -- https://download2.dynamsoft.com/packages/dynamsoft-barcode-reader@10.0.20/dist/dbr.js -- https://download2.dynamsoft.com/packages/dynamsoft-capture-vision-router@2.0.31/dist/cvr.js -- https://download2.dynamsoft.com/packages/dynamsoft-camera-enhancer@4.0.1/dist/dce.js - -However, please **DO NOT** use `download2.dynamsoft.com` resources in a production application as they are for temporary testing purposes only. Instead, you can try hosting the SDK yourself. - -#### Host the SDK yourself - -Besides using the public CDN, you can also download the SDK and host its files on your own server or a commercial CDN before including it in your application. - -Options to download the SDK: - -- From the website - - [Download Dynamsoft Barcode Reader JavaScript Package](https://www.dynamsoft.com/barcode-reader/downloads/?ver=10.0.20&utm_source=guide&product=dbr&package=js) - -- yarn - - ```cmd - yarn add dynamsoft-core@3.0.32 --save - yarn add dynamsoft-license@3.0.20 --save - yarn add dynamsoft-utility@1.0.21 --save - yarn add dynamsoft-barcode-reader@10.0.20 --save - yarn add dynamsoft-capture-vision-router@2.0.31 --save - yarn add dynamsoft-camera-enhancer@4.0.1 --save - yarn add dynamsoft-capture-vision-std@1.0.0 --save - yarn add dynamsoft-image-processing@2.0.30 --save - ``` - -- npm - - ```cmd - npm install dynamsoft-core@3.0.32 --save - npm install dynamsoft-license@3.0.20 --save - npm install dynamsoft-utility@1.0.21 --save - npm install dynamsoft-barcode-reader@10.0.20 --save - npm install dynamsoft-capture-vision-router@2.0.31 --save - npm install dynamsoft-camera-enhancer@4.0.1 --save - npm install dynamsoft-capture-vision-std@1.0.0 --save - npm install dynamsoft-image-processing@2.0.30 --save - ``` - -Depending on how you downloaded the SDK and how you intend to use it, you can typically include it like this: - -```html - - - - - - -``` - -or - -```html - - - - - - -``` - -or - -```typescript -import { CoreModule, EnumCapturedResultItemType } from 'dynamsoft-core' -import { LicenseManager } from 'dynamsoft-license'; -import { CapturedResultReceiver, CaptureVisionRouter, type SimplifiedCaptureVisionSettings } from "dynamsoft-capture-vision-router"; -import { CameraEnhancer, CameraView } from "dynamsoft-camera-enhancer"; -import { DecodedBarcodesResult } from 'dynamsoft-barcode-reader'; -import { MultiFrameResultCrossFilter } from 'dynamsoft-utility'; -``` - -*Note*: - -* Certain legacy web application servers may lack support for the `application/wasm` mimetype for .wasm files. To address this, you have two options: - 1. Upgrade your web application server to one that supports the `application/wasm` mimetype. - 2. Manually define the mimetype on your server. You can refer to the following resources for guidance: - 1. [Apache](https://developer.mozilla.org/en-US/docs/Learn/Server-side/Apache_Configuration_htaccess#media_types_and_character_encodings) - 2. [IIS](https://docs.microsoft.com/en-us/iis/configuration/system.webserver/staticcontent/mimemap) - 3. [Nginx](https://www.nginx.com/resources/wiki/start/topics/examples/full/#mime-types) - -* To work properly, the SDK requires a few engine files, which are relatively large and may take quite a few seconds to download. We recommend that you set a longer cache time for these engine files, to maximize the performance of your web application. - - ```cmd - Cache-Control: max-age=31536000 - ``` - - Reference: [Cache-Control](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control). - -### Prepare the SDK - -Before using the SDK, you need to configure a few things. - -#### Specify the license - -To enable the SDK's functionality, you must provide a valid license. Utilize the API function initLicense to set your license key. - -```javascript -Dynamsoft.License.LicenseManager.initLicense("DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9"); -``` - -As previously stated, the key "DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9" serves as a test license valid for 24 hours, applicable to any newly authorized browser. To test the SDK further, you can request a 30-day free trial license via the Request a Trial License link. - -> Upon registering a Dynamsoft account and obtaining the SDK package from the official website, Dynamsoft will automatically create a 30-day free trial license and embed the corresponding license key into all the provided SDK samples. - -#### Specify the location of the "engine" files (optional) - -This is usually only required with frameworks like Angular or React, etc. where the referenced JavaScript files such as `cvr.js`, `dbr.js` are compiled into another file. - -The purpose is to tell the SDK where to find the engine files (\*.worker.js, \*.wasm.js and \*.wasm, etc.). The API is called `Dynamsoft.Core.CoreModule.engineResourcePaths`: - -```javascript -//The following code uses the jsDelivr CDN, feel free to change it to your own location of these files -Dynamsoft.Core.CoreModule.engineResourcePaths.core = "https://cdn.jsdelivr.net/npm/dynamsoft-core@3.0.32/dist/"; -Dynamsoft.Core.CoreModule.engineResourcePaths.license = "https://cdn.jsdelivr.net/npm/dynamsoft-license@3.0.20/dist/"; -Dynamsoft.Core.CoreModule.engineResourcePaths.dbr = "https://cdn.jsdelivr.net/npm/dynamsoft-barcode-reader@10.0.20/dist/"; -Dynamsoft.Core.CoreModule.engineResourcePaths.cvr = "https://cdn.jsdelivr.net/npm/dynamsoft-capture-vision-router@2.0.31/dist/"; -Dynamsoft.Core.CoreModule.engineResourcePaths.dce = "https://cdn.jsdelivr.net/npm/dynamsoft-camera-enhancer@4.0.1/dist/"; -Dynamsoft.Core.CoreModule.engineResourcePaths.std = "https://cdn.jsdelivr.net/npm/dynamsoft-capture-vision-std@1.0.0/dist/"; -Dynamsoft.Core.CoreModule.engineResourcePaths.dip = "https://cdn.jsdelivr.net/npm/dynamsoft-image-processing@2.0.30/dist/" -``` - -### Set up and start image processing - -#### Preload the module - -The image processing logic is encapsulated within .wasm library files, and these files may require some time for downloading. To enhance the speed, we advise utilizing the following method to preload the libraries. - -```js -// Preload the .wasm files -await Dynamsoft.Core.CoreModule.loadWasm(["cvr", "dbr"]); -``` - -#### Create a CaptureVisionRouter object - -To use the SDK, we first create a `CaptureVisionRouter` object. - -```javascript -Dynamsoft.License.LicenseManager.initLicense("DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9"); - -let cvRouter = null; -try { - cvRouter = await Dynamsoft.CVR.CaptureVisionRouter.createInstance(); -} catch (ex) { - console.error(ex); -} -``` - -*Tip*: - -When creating a `CaptureVisionRouter` object within a function which may be called more than once, it's best to use a "helper" variable to avoid double creation such as `tempRouter` in the following code - -```javascript -Dynamsoft.License.LicenseManager.initLicense("DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9"); - -let tempRouter = null; -let cvRouter = null; - -document.getElementById('btn-scan').addEventListener('click', async () => { - try { - cvRouter = await (tempRouter = tempRouter || Dynamsoft.CVR.CaptureVisionRouter.createInstance()); - } catch (ex) { - console.error(ex); - } -}); -``` - -#### Connect an image source - -The `CaptureVisionRouter` object, denoted as `cvRouter`, is responsible for handling images provided by an image source. In our scenario, we aim to detect barcodes directly from a live video stream. To facilitate this, we initialize a `CameraEnhancer` object, identified as `cameraEnhancer`, which is specifically designed to capture image frames from the video feed and subsequently forward them to `cvRouter`. - -To enable video streaming on the webpage, we create a `CameraView` object referred to as `cameraView`, which is then passed to `cameraEnhancer`, and its content is displayed on the webpage. - -```html -
-``` - -```javascript -let cameraView = await Dynamsoft.DCE.CameraView.createInstance(); -let cameraEnhancer = await Dynamsoft.DCE.CameraEnhancer.createInstance(cameraView); -document.querySelector("#camera-view-container").append(cameraView.getUIElement()); -cvRouter.setInput(cameraEnhancer); -``` - -#### Register a result receiver - -Once the image processing is complete, the results are sent to all the registered `CapturedResultReceiver` objects. Each `CapturedResultReceiver` object may encompass one or multiple callback functions associated with various result types. In our particular case, our focus is on identifying barcodes within the images, so it's sufficient to define the callback function `onDecodedBarcodesReceived`: - -```javascript -const resultsContainer = document.querySelector("#results"); -const resultReceiver = new Dynamsoft.CVR.CapturedResultReceiver(); -resultReceiver.onDecodedBarcodesReceived = (result) => { - if (result.barcodeResultItems.length > 0) { - resultsContainer.textContent = ''; - for (let item of result.barcodeResultItems) { - // In this example, the barcode result is shown on the page beneath the video - resultsContainer.textContent += `${item.formatString}: ${item.text}\n\n`; - } - } -}; -cvRouter.addResultReceiver(resultReceiver); -``` - -You can also write code like this. It is the same. - -```javascript -const resultsContainer = document.querySelector("#results"); -cvRouter.addResultReceiver({ onDecodedBarcodesReceived: (result) => { - if (result.barcodeResultItems.length > 0) { - resultsContainer.textContent = ''; - for (let item of result.barcodeResultItems) { - // In this example, the barcode result is shown on the page beneath the video - resultsContainer.textContent += `${item.formatString}: ${item.text}\n\n`; - } - } -}}); -``` - -Check out [CapturedResultReceiver](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/core/basic-structures/captured-result-receiver.html) for more information. - -#### Start the process - -With the setup now complete, we can proceed to process the images in two straightforward steps: - -1. Initiate the image source to commence image acquisition. In our scenario, we invoke the `open()` method on `cameraEnhancer` to initiate video streaming and simultaneously initiate the collection of images. These collected images will be dispatched to `cvRouter` as per its request. -2. Define a preset template to commence image processing. In our case, we utilize the "ReadSingleBarcode" template, specifically tailored for processing images containing a single barcode. - -```javascript -await cameraEnhancer.open(); -await cvRouter.startCapturing("ReadSingleBarcode"); -``` - -*Note*: - -* `cvRouter` is engineered to consistently request images from the image source. -* Various preset templates are at your disposal for barcode reading: - -| Template Name | Function Description | -| ------------------------------ | -------------------------------------------------------------- | -| **ReadBarcodes_Default** | Scans a single barcode. | -| **ReadSingleBarcode** | Quickly scans a single barcode. | -| **ReadBarcodes_SpeedFirst** | Prioritizes speed in scanning multiple barcodes. | -| **ReadBarcodes_ReadRateFirst** | Maximizes the number of barcodes read. | -| **ReadBarcodes_Balance** | Balances speed and quantity in reading multiple barcodes. | -| **ReadDenseBarcodes** | Specialized in reading barcodes with high information density. | -| **ReadDistantBarcodes** | Capable of reading barcodes from extended distances. | - -### Customize the process - -#### Adjust the preset template settings - -When making adjustments to some basic tasks, we often only need to modify [SimplifiedCaptureVisionSettings](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/capture-vision-router/interfaces/simplified-capture-vision-settings.html). - -##### Change barcode settings - -The preset templates can be updated to meet different requirements. For example, the following code limits the barcode format to QR code. - -```javascript -let settings = await cvRouter.getSimplifiedSettings("ReadSingleBarcode"); -settings.barcodeSettings.barcodeFormatIds = - Dynamsoft.DBR.EnumBarcodeFormat.BF_QR_CODE; -await cvRouter.updateSettings("ReadSingleBarcode", settings); -await cvRouter.startCapturing("ReadSingleBarcode"); -``` - -For a list of adjustable barcode settings, check out [SimplifiedBarcodeReaderSettings](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/interfaces/simplified-barcode-reader-settings.html). - -##### Retrieve the original image - -Additionally, we have the option to modify the template to retrieve the original image containing the barcode. - -```javascript -let settings = await cvRouter.getSimplifiedSettings("ReadSingleBarcode"); -settings.capturedResultItemTypes |= - Dynamsoft.Core.EnumCapturedResultItemType.CRIT_ORIGINAL_IMAGE; -await cvRouter.updateSettings("ReadSingleBarcode", settings); -await cvRouter.startCapturing("ReadSingleBarcode"); -``` - -Limit the barcode format to QR code, and retrieve the original image containing the barcode, at the same time. - -```javascript -let settings = await cvRouter.getSimplifiedSettings("ReadSingleBarcode"); -settings.capturedResultItemTypes = - Dynamsoft.DBR.EnumBarcodeFormat.BF_QR_CODE | - Dynamsoft.Core.EnumCapturedResultItemType.CRIT_ORIGINAL_IMAGE; -await cvRouter.updateSettings("ReadSingleBarcode", settings); -await cvRouter.startCapturing("ReadSingleBarcode"); -``` - -Please be aware that it is necessary to update the `CapturedResultReceiver` object to obtain the original image. For instance: - -```javascript -resultReceiver.onCapturedResultReceived = (result) => { - let barcodes = result.items.filter((item) => - item.type === Dynamsoft.Core.EnumCapturedResultItemType.CRIT_BARCODE - ); - if (barcodes.length > 0) { - let image = result.items.filter((item) => - item.type === Dynamsoft.Core.EnumCapturedResultItemType.CRIT_ORIGINAL_IMAGE - )[0].imageData; - // The image that we found the barcode(s) on. - } -}; -``` - -##### Change reading frequency to save power - -The SDK is initially configured to process images sequentially without any breaks. Although this setup maximizes performance, it can lead to elevated power consumption, potentially causing the device to overheat. In many cases, it's possible to reduce the reading speed while still satisfying business requirements. The following code snippet illustrates how to adjust the SDK to process an image every 500 milliseconds: - -> Please bear in mind that in the following code, if an image's processing time is shorter than 500 milliseconds, the SDK will wait for the full 500 milliseconds before proceeding to process the next image. Conversely, if an image's processing time exceeds 500 milliseconds, the subsequent image will be processed immediately upon completion. - -```javascript -let settings = await cvRouter.getSimplifiedSettings("ReadSingleBarcode"); -settings.minImageCaptureInterval = 500; -await cvRouter.updateSettings("ReadSingleBarcode", settings); -await cvRouter.startCapturing("ReadSingleBarcode"); -``` - -##### Specify a scan region - -You can use the parameter `roi` (region of interest) together with the parameter `roiMeasuredInPercentage` to configure the SDK to only read a specific region on the image frames. For example, the following code limits the reading in the center 25%( = 50% * 50%) of the image frames: - -```javascript -let settings = await cvRouter.getSimplifiedSettings("ReadSingleBarcode"); -settings.roiMeasuredInPercentage = true; -settings.roi.points = [ - { x: 25, y: 25 }, - { x: 75, y: 25 }, - { x: 75, y: 75 }, - { x: 25, y: 75 }, -]; -await cvRouter.updateSettings("ReadSingleBarcode", settings); -await cvRouter.startCapturing("ReadSingleBarcode"); -``` - -While the code above accomplishes the task, a more effective approach is to restrict the scan region directly at the image source, as demonstrated in the following code snippet. - -> * With the region configured at the image source, the images are cropped right before they are gathered for processing, eliminating the necessity to modify the processing settings further. -> * `cameraEnhancer` elevates interactivity by overlaying a mask on the video, providing a clear delineation of the scanning region. -> * See also: [CameraEnhancer::setScanRegion](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/acquisition.html#setscanregion) - -```javascript -cameraEnhancer = await Dynamsoft.DCE.CameraEnhancer.createInstance(cameraView); -cameraEnhancer.setScanRegion({ - x: 25, - y: 25, - width: 50, - height: 50, - isMeasuredInPercentage: true, -}); -``` - - - -#### Edit the preset templates directly - -The preset templates have a lot more settings that can be customized to best suit your use case. If you [download the SDK from Dynamsoft website](https://www.dynamsoft.com/barcode-reader/downloads/1000003-confirmation/), you can find the templates under - -* "/dynamsoft-barcode-reader-js-10.0.20/dynamsoft/resources/barcode-reader/templates/" - -Upon completing the template editing, you can invoke the `initSettings` method and provide it with the template path as an argument. - -```javascript -await cvRouter.initSettings("PATH-TO-THE-FILE"); //e.g. "https://your-website/ReadSingleBarcode.json") -await cvRouter.startCapturing("ReadSingleBarcode"); // Make sure the name matches one of the CaptureVisionTemplates in the -``` - -#### Filter the results (Important) - -While processing video frames, it's common for the same barcode to be detected multiple times. To enhance the user experience, we can use [MultiFrameResultCrossFilter](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/utility/multi-frame-result-cross-filter.html) object, having two options currently at our disposal: - -##### Option 1: Verify results across multiple frames - -```js -let filter = new Dynamsoft.Utility.MultiFrameResultCrossFilter(); -filter.enableResultCrossVerification(Dynamsoft.Core.EnumCapturedResultItemType.CRIT_BARCODE, true); -await cvRouter.addResultFilter(filter); -``` - -*Note*: - -* `enableResultCrossVerification` was designed to cross-validate the outcomes across various frames in a video streaming scenario, enhancing the reliability of the final results. This validation is particularly crucial for barcodes with limited error correction capabilities, such as 1D codes. - -##### Option 2: Eliminate redundant results detected within a short time frame - -```js -let filter = new Dynamsoft.Utility.MultiFrameResultCrossFilter(); -filter.enableResultDeduplication(Dynamsoft.Core.EnumCapturedResultItemType.CRIT_BARCODE, true); -await cvRouter.addResultFilter(filter); -``` - -*Note*: - -* `enableResultDeduplication` was designed to prevent high usage in video streaming scenarios, addressing the repetitive processing of the same code within a short period of time. - -Initially, the filter is set to forget a result 3 seconds after it is first received. During this time frame, if an identical result appears, it is ignored. - -> It's important to know that in version 9.x or earlier, the occurrence of an identical result would reset the timer, thus reinitiating the 3-second count at that point. However, in version 10.0.20 and later, an identical result no longer resets the timer but is instead disregarded, and the duration count continues uninterrupted. - -Under certain circumstances, this duration can be extended with the method `setDuplicateForgetTime()`. - -```js -let filter = new Dynamsoft.Utility.MultiFrameResultCrossFilter(); -filter.setDuplicateForgetTime(5000); // Extend the duration to 5 seconds. -await cvRouter.addResultFilter(filter); -``` - -You can also enable both options at the same time: - -```js -let filter = new Dynamsoft.Utility.MultiFrameResultCrossFilter(); -filter.enableResultCrossVerification(Dynamsoft.Core.EnumCapturedResultItemType.CRIT_BARCODE, true); -filter.enableResultDeduplication(Dynamsoft.Core.EnumCapturedResultItemType.CRIT_BARCODE, true); -filter.setDuplicateForgetTime(5000); -await cvRouter.addResultFilter(filter); -``` - -#### Add feedback - -When a barcode is detected within the video stream, its position is immediately displayed within the video. Furthermore, utilizing the "Dynamsoft Camera Enhancer" SDK, we can introduce feedback mechanisms, such as emitting a "beep" sound or triggering a "vibration". - -The following code snippet adds a "beep" sound for when a barcode is found: - -```js -const resultReceiver = new Dynamsoft.CVR.CapturedResultReceiver(); -resultReceiver.onDecodedBarcodesReceived = (result) => { - if (result.barcodeResultItems.length > 0) { - Dynamsoft.DCE.Feedback.beep(); - } -}; -cvRouter.addResultReceiver(resultReceiver); -``` - -### Customize the UI - -The UI is part of the auxiliary SDK "Dynamsoft Camera Enhancer", read more on how to [customize the UI](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/user-guide/index.html#customize-the-ui). - -## API Documentation - -You can check out the detailed documentation about the APIs of the SDK at -[https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/?ver=10.0.20](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/?ver=10.0.20). - -## System Requirements - -DBR requires the following features to work: - -- Secure context (HTTPS deployment) - - When deploying your application / website for production, make sure to serve it via a secure HTTPS connection. This is required for two reasons - - - Access to the camera video stream is only granted in a security context. Most browsers impose this restriction. - > Some browsers like Chrome may grant the access for `http://127.0.0.1` and `http://localhost` or even for pages opened directly from the local disk (`file:///...`). This can be helpful for temporary development and test. - - - Dynamsoft License requires a secure context to work. - -- `WebAssembly`, `Blob`, `URL`/`createObjectURL`, `Web Workers` - - The above four features are required for the SDK to work. - -- `MediaDevices`/`getUserMedia` - - This API is required for in-browser video streaming. - -- `getSettings` - - This API inspects the video input which is a `MediaStreamTrack` object about its constrainable properties. - -The following table is a list of supported browsers based on the above requirements: - - | Browser Name | Version | - | :----------: | :--------------: | - | Chrome | v78+1 | - | Firefox | v62+1 | - | Edge | v79+ | - | Safari | v14+ | - - 1 devices running iOS needs to be on iOS 14.3+ for camera video streaming to work in Chrome, Firefox or other Apps using webviews. - -Apart from the browsers, the operating systems may impose some limitations of their own that could restrict the use of the SDK. Browser compatibility ultimately depends on whether the browser on that particular operating system supports the features listed above. - -## How to Upgrade - -If you want to upgrade the SDK from an old version to a newer one, please see [how to upgrade](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/upgrade-guide/index.html?ver=10.0.20&utm_source=guide). - -## Release Notes - -Learn about what are included in each release at [https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/release-notes/index.html](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/release-notes/index.html?ver=10.0.20&utm_source=guide). - -## Next Steps - -Now that you have got the SDK integrated, you can choose to move forward in the following directions - -1. Check out the [Official Samples and Demo](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/index.html?ver=10.0.20) -2. Learn about the [APIs of the SDK](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/index.html?ver=10.0.20) diff --git a/programming/javascript/user-guide/index-v10.0.21.md b/programming/javascript/user-guide/index-v10.0.21.md deleted file mode 100644 index 7da425c2..00000000 --- a/programming/javascript/user-guide/index-v10.0.21.md +++ /dev/null @@ -1,799 +0,0 @@ ---- -layout: default-layout -title: v10.0.21 User Guide - Dynamsoft Barcode Reader JavaScript Edition -description: This is the user guide of Dynamsoft Barcode Reader JavaScript SDK. -keywords: user guide, javascript, js -breadcrumbText: User Guide -noTitleIndex: true -needGenerateH3Content: true -needAutoGenerateSidebar: true -schema: schemas/dynamsoft-facilitates-mit-research-schema.json ---- - - - -# Barcode Reader for Your Website - User Guide - -[Dynamsoft Barcode Reader JavaScript Edition](https://www.dynamsoft.com/barcode-reader/sdk-javascript/) (DBR-JS) is equipped with industry-leading algorithms for exceptional speed, accuracy and read rates in barcode reading. Using its well-designed API, you can turn your web page into a barcode scanner with just a few lines of code. - -![version](https://img.shields.io/npm/v/dynamsoft-barcode-reader.svg) -![downloads](https://img.shields.io/npm/dm/dynamsoft-barcode-reader.svg) -![jsdelivr](https://img.shields.io/jsdelivr/npm/hm/dynamsoft-barcode-reader.svg) - -![version](https://img.shields.io/npm/v/dynamsoft-javascript-barcode.svg) -![downloads](https://img.shields.io/npm/dm/dynamsoft-javascript-barcode.svg) -![jsdelivr](https://img.shields.io/jsdelivr/npm/hm/dynamsoft-javascript-barcode.svg) - -Once the DBR-JS SDK gets integrated into your web page, your users can access a camera via the browser and read barcodes directly from its video input. - -In this guide, you will learn step by step on how to integrate the DBR-JS SDK into your website. - -Table of Contents - -- [Barcode Reader for Your Website - User Guide](#barcode-reader-for-your-website---user-guide) - - [Hello World - Simplest Implementation](#hello-world---simplest-implementation) - - [Understand the code](#understand-the-code) - - [About the code](#about-the-code) - - [Run the example](#run-the-example) - - [Building your own page](#building-your-own-page) - - [Include the SDK](#include-the-sdk) - - [Use a public CDN](#use-a-public-cdn) - - [Host the SDK yourself (optional)](#host-the-sdk-yourself-optional) - - [Prepare the SDK](#prepare-the-sdk) - - [Specify the license](#specify-the-license) - - [Specify the location of the "engine" files (optional)](#specify-the-location-of-the-engine-files-optional) - - [Set up and start image processing](#set-up-and-start-image-processing) - - [Preload the module](#preload-the-module) - - [Create a CaptureVisionRouter object](#create-a-capturevisionrouter-object) - - [Connect an image source](#connect-an-image-source) - - [Register a result receiver](#register-a-result-receiver) - - [Start the process](#start-the-process) - - [Customize the process](#customize-the-process) - - [Adjust the preset template settings](#adjust-the-preset-template-settings) - - [Change barcode settings](#change-barcode-settings) - - [Retrieve the original image](#retrieve-the-original-image) - - [Change reading frequency to save power](#change-reading-frequency-to-save-power) - - [Specify a scan region](#specify-a-scan-region) - - [Edit the preset templates directly](#edit-the-preset-templates-directly) - - [Filter the results (Important)](#filter-the-results-important) - - [Option 1: Verify results across multiple frames](#option-1-verify-results-across-multiple-frames) - - [Option 2: Eliminate redundant results detected within a short time frame](#option-2-eliminate-redundant-results-detected-within-a-short-time-frame) - - [Add feedback](#add-feedback) - - [Customize the UI](#customize-the-ui) - - [API Documentation](#api-documentation) - - [System Requirements](#system-requirements) - - [How to Upgrade](#how-to-upgrade) - - [Release Notes](#release-notes) - - [Next Steps](#next-steps) - -**Popular Examples** - -- Hello World - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v10.0.21/hello-world/hello-world.html) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/hello-world/hello-world.html?ver=10.0.21&utm_source=guide) -- Angular App - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v10.0.21/hello-world/angular) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/hello-world/angular/dist/angular/?ver=10.0.21&utm_source=guide) -- React App - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v10.0.21/hello-world/react) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/hello-world/react/build/?ver=10.0.21&utm_source=guide) -- Vue App - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v10.0.21/hello-world/vue) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/hello-world/vue/dist/?ver=10.0.21&utm_source=guide) -- PWA App - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v10.0.21/hello-world/pwa) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/hello-world/pwa/helloworld-pwa.html?ver=10.0.21&utm_source=guide) -- WebView in Android and iOS - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/v10.0.21/hello-world/webview) -- Read Driver Licenses - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v10.0.21/use-case/read-a-drivers-license.html) \| [Run](https://demo.dynamsoft.com/samples/dbr/js/use-case/read-a-drivers-license.html?ver=10.0.21&utm_source=guide) -- Fill A Form - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v10.0.21/use-case/fill-a-form-with-barcode-reading.html) \| [Run](https://demo.dynamsoft.com/samples/dbr/js/use-case/fill-a-form-with-barcode-reading.html?ver=10.0.21&utm_source=guide) -- Show result information on the video - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v10.0.21/use-case/show-result-texts-on-the-video.html) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/use-case/show-result-texts-on-the-video.html?ver=10.0.21&utm_source=guide) -- Debug Camera and Collect Video Frame - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v10.0.21/others/debug) - -You can also: - -- Try the Official Demo - [Run](https://demo.dynamsoft.com/barcode-reader-js/?ver=10.0.21&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-demo/) -- Try Online Examples - [Run](https://demo.dynamsoft.com/Samples/DBR/JS/index.html?ver=10.0.21&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/v10.0.21/) - -## Hello World - Simplest Implementation - -Let's start with the "Hello World" example of the DBR-JS SDK which demonstrates how to use the minimum code to enable a web page to read barcodes from a live video stream. - -**Basic Requirements** - - Internet connection - - [A supported browser](#system-requirements) - - Camera access - -### Understand the code - -The complete code of the "Hello World" example is shown below - -```html - - - -
- - - - - -``` - - - -

- - Code in Github - -   - - Run via JSFiddle - -   - - Run in Dynamsoft - -

- ------ - -#### About the code - -- `Dynamsoft.License.LicenseManager.initLicense()`: This method initializes the license for using the SDK in the application. Note that the string "**DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9**" used in this example points to an online license that requires a network connection to work. Read more on [Specify the license](#specify-the-license). - -- `Dynamsoft.CVR.CaptureVisionRouter.createInstance()`: This method creates a `CaptureVisionRouter` object `cvRouter` which controls the entire process in three steps: - - **Retrieve Images from the Image Source** - - `cvRouter` connects to the image source through the [ImageSourceAdapter](https://www.dynamsoft.com/capture-vision/docs/core/architecture/input.html#image-source-adapter?lang=js) interface with the method `setInput()`. - ```js - cvRouter.setInput(cameraEnhancer); - ``` - > The image source in our case is a [CameraEnhancer](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/user-guide/index.html) object created with `Dynamsoft.DCE.CameraEnhancer.createInstance(cameraView)` - - **Coordinate Image-Processing Tasks** - - The coordination happens behind the scenes. `cvRouter` starts the process by specifying a preset template "ReadSingleBarcode" in the method `startCapturing()`. - ```js - cvRouter.startCapturing("ReadSingleBarcode"); - ``` - - **Dispatch Results to Listening Objects** - - The processing results are returned through the [CapturedResultReceiver](https://www.dynamsoft.com/capture-vision/docs/core/architecture/output.html#captured-result-receiver?lang=js) interface. The `CapturedResultReceiver` object is registered to `cvRouter` via the method `addResultReceiver()`. For more information, please check out [Register a result receiver](#register-a-result-receiver). - ```js - cvRouter.addResultReceiver({/*The-CapturedResultReceiver-Object"*/}); - ``` - - Also note that reading from video is extremely fast and there could be many duplicate results. We can use a [filter](#filter-the-results-important) with result deduplication enabled to filter out the duplicate results. The object is registered to `cvRouter` via the method `addResultFilter()`. - ```js - cvRouter.addResultFilter(filter); - ``` - -> Read more on [Capture Vision Router](https://www.dynamsoft.com/capture-vision/docs/core/architecture/#capture-vision-router). - -### Run the example - -You can run the example deployed to [the Dynamsoft Demo Server](https://demo.dynamsoft.com/Samples/DBR/JS/hello-world/hello-world.html?ver=10.0.21&utm_source=guide) or test it with [JSFiddle code editor](https://jsfiddle.net/DynamsoftTeam/pL4e7yrd/). - -You will be asked to allow access to your camera, after which the video will be displayed on the page. After that, you can point the camera at a barcode to read it. - -When a barcode is decoded, you will see the result text show up under the video and the barcode location will be highlighted in the video feed. - -Alternatively, you can test locally by copying and pasting the code shown above into a local file (e.g. "hello-world.html") and opening it in your browser. - -*Note*: - -If you open the web page as `file:///` or `http://` , the camera may not work correctly because the [MediaDevices: getUserMedia()](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia) method only works in secure contexts (HTTPS), in some or all supporting browsers. - -To make sure your web application can access the camera, please configure your web server to support HTTPS. The following links may help. - -1. NGINX: [Configuring HTTPS servers](https://nginx.org/en/docs/http/configuring_https_servers.html) -2. IIS: [How to create a Self Signed Certificate in IIS](https://aboutssl.org/how-to-create-a-self-signed-certificate-in-iis/) -3. Tomcat: [Setting Up SSL on Tomcat in 5 minutes](https://dzone.com/articles/setting-ssl-tomcat-5-minutes) -4. Node.js: [npm tls](https://nodejs.org/docs/v0.4.1/api/tls.html) - -If the test doesn't go as expected, you can [contact us](https://www.dynamsoft.com/company/contact/?ver=10.0.21&utm_source=guide&product=dbr&package=js). - -## Building your own page - -### Include the SDK - -To utilize the SDK, the initial step involves including the corresponding resource files: - -* `core.js` encompasses common classes, interfaces, and enumerations that are shared across all Dynamsoft SDKs. -* `license.js` introduces the `LicenseManager` class, which manages the licensing for all Dynamsoft SDKs. -* `utility.js` encompasses auxiliary classes that are shared among all Dynamsoft SDKs. -* `dbr.js` defines interfaces and enumerations specifically tailored to the barcode reader module. -* `cvr.js` introduces the `CaptureVisionRouter` class, which governs the entire image processing workflow. -* `dce.js` comprises classes that offer camera support and basic user interface functionalities. - -For simplification, starting from version 10.0.21, we introduced `dbr.bundle.js`. Including this file is equivalent to incorporating all six packages. - -#### Use a public CDN - -The simplest way to include the SDK is to use either the [jsDelivr](https://jsdelivr.com/) or [UNPKG](https://unpkg.com/) CDN. The "hello world" example above uses **jsDelivr**. - -- jsDelivr - - ```html - - - - - - - ``` - - Or just - - ```html - - ``` - -- UNPKG - - ```html - - - - - - - ``` - - Or just - - ```html - - ``` - -In some rare cases (such as some restricted areas), you might not be able to access the CDN. If this happens, you can use the following files for the test. - -- https://download2.dynamsoft.com/packages/dynamsoft-core@3.0.33/dist/core.js -- https://download2.dynamsoft.com/packages/dynamsoft-license@3.0.40/dist/license.js -- https://download2.dynamsoft.com/packages/dynamsoft-utility@1.0.21/dist/utility.js -- https://download2.dynamsoft.com/packages/dynamsoft-barcode-reader@10.0.21/dist/dbr.js -- https://download2.dynamsoft.com/packages/dynamsoft-capture-vision-router@2.0.32/dist/cvr.js -- https://download2.dynamsoft.com/packages/dynamsoft-camera-enhancer@4.0.1/dist/dce.js -- or bundle: https://download2.dynamsoft.com/packages/dynamsoft-barcode-reader@10.0.21/dist/dbr.bundle.js - -However, please **DO NOT** use `download2.dynamsoft.com` resources in a production application as they are for temporary testing purposes only. Instead, you can try hosting the SDK yourself. - -#### Host the SDK yourself (optional) - -Besides using the public CDN, you can also download the SDK and host its files on your own server or a commercial CDN before including it in your application. - -Options to download the SDK: - -- From the website - - [Download Dynamsoft Barcode Reader JavaScript Package](https://www.dynamsoft.com/barcode-reader/downloads/?ver=10.0.21&utm_source=guide&product=dbr&package=js) - -- yarn - - ```cmd - yarn add dynamsoft-core@3.0.33 --save - yarn add dynamsoft-license@3.0.40 --save - yarn add dynamsoft-utility@1.0.21 --save - yarn add dynamsoft-barcode-reader@10.0.21 --save - yarn add dynamsoft-capture-vision-router@2.0.32 --save - yarn add dynamsoft-camera-enhancer@4.0.1 --save - yarn add dynamsoft-capture-vision-std@1.0.0 --save - yarn add dynamsoft-image-processing@2.0.30 --save - ``` - -- npm - - ```cmd - npm install dynamsoft-core@3.0.33 --save - npm install dynamsoft-license@3.0.40 --save - npm install dynamsoft-utility@1.0.21 --save - npm install dynamsoft-barcode-reader@10.0.21 --save - npm install dynamsoft-capture-vision-router@2.0.32 --save - npm install dynamsoft-camera-enhancer@4.0.1 --save - npm install dynamsoft-capture-vision-std@1.0.0 --save - npm install dynamsoft-image-processing@2.0.30 --save - ``` - -Depending on how you downloaded the SDK and how you intend to use it, you can typically include it like this - -- From the website - - ```html - - - - - - - ``` - - Or just - - ```html - - ``` - -- yarn or npm - - ```html - - - - - - - ``` - - Or just - - ```html - - ``` - -*Note*: - -* Certain legacy web application servers may lack support for the `application/wasm` mimetype for .wasm files. To address this, you have two options: - 1. Upgrade your web application server to one that supports the `application/wasm` mimetype. - 2. Manually define the mimetype on your server. You can refer to the following resources for guidance: - 1. [Apache](https://developer.mozilla.org/en-US/docs/Learn/Server-side/Apache_Configuration_htaccess#media_types_and_character_encodings) - 2. [IIS](https://docs.microsoft.com/en-us/iis/configuration/system.webserver/staticcontent/mimemap) - 3. [Nginx](https://www.nginx.com/resources/wiki/start/topics/examples/full/#mime-types) - -* To work properly, the SDK requires a few engine files, which are relatively large and may take quite a few seconds to download. We recommend that you set a longer cache time for these engine files, to maximize the performance of your web application. - - ```cmd - Cache-Control: max-age=31536000 - ``` - - Reference: [Cache-Control](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control). - -### Prepare the SDK - -Before using the SDK, you need to configure a few things. - -#### Specify the license - -To enable the SDK's functionality, you must provide a valid license. Utilize the API function initLicense to set your license key. - -```javascript -Dynamsoft.License.LicenseManager.initLicense("DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9"); -``` - -As previously stated, the key "DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9" serves as a test license valid for 24 hours, applicable to any newly authorized browser. To test the SDK further, you can request a 30-day free trial license via the Request a Trial License link. - -> Upon registering a Dynamsoft account and obtaining the SDK package from the official website, Dynamsoft will automatically create a 30-day free trial license and embed the corresponding license key into all the provided SDK samples. - -#### Specify the location of the "engine" files (optional) - -This is usually only required with frameworks like Angular or React, etc. where the referenced JavaScript files such as `cvr.js`, `dbr.js` are compiled into another file. - -The purpose is to tell the SDK where to find the engine files (\*.worker.js, \*.wasm.js and \*.wasm, etc.). The API is called `Dynamsoft.Core.CoreModule.engineResourcePaths`: - -```javascript -//The following code uses the jsDelivr CDN, feel free to change it to your own location of these files -Object.assign(Dynamsoft.Core.CoreModule.engineResourcePaths, { - std: "https://cdn.jsdelivr.net/npm/dynamsoft-capture-vision-std@1.0.0/dist/", - dip: "https://cdn.jsdelivr.net/npm/dynamsoft-image-processing@2.0.30/dist/", - core: "https://cdn.jsdelivr.net/npm/dynamsoft-core@3.0.33/dist/", - license: "https://cdn.jsdelivr.net/npm/dynamsoft-license@3.0.40/dist/", - cvr: "https://cdn.jsdelivr.net/npm/dynamsoft-capture-vision-router@2.0.32/dist/", - dbr: "https://cdn.jsdelivr.net/npm/dynamsoft-barcode-reader@10.0.21/dist/", - dce: "https://cdn.jsdelivr.net/npm/dynamsoft-camera-enhancer@4.0.1/dist/" -}); -``` - -### Set up and start image processing - -#### Preload the module - -The image processing logic is encapsulated within .wasm library files, and these files may require some time for downloading. To enhance the speed, we advise utilizing the following method to preload the libraries. - -```js -// Preload the .wasm files -await Dynamsoft.Core.CoreModule.loadWasm(["cvr", "dbr"]); -``` - -#### Create a CaptureVisionRouter object - -To use the SDK, we first create a `CaptureVisionRouter` object. - -```javascript -Dynamsoft.License.LicenseManager.initLicense("DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9"); - -let cvRouter = null; -try { - cvRouter = await Dynamsoft.CVR.CaptureVisionRouter.createInstance(); -} catch (ex) { - console.error(ex); -} -``` - -*Tip*: - -When creating a `CaptureVisionRouter` object within a function which may be called more than once, it's best to use a "helper" variable to avoid double creation such as `pRouter` in the following code: - -```javascript -Dynamsoft.License.LicenseManager.initLicense("DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9"); - -let pCvRouter = null; // promise of router -let cvRouter = null; - -document.getElementById('btn-scan').addEventListener('click', async () => { - try { - cvRouter = await (pCvRouter = pCvRouter || Dynamsoft.CVR.CaptureVisionRouter.createInstance()); - } catch (ex) { - console.error(ex); - } -}); -``` - -#### Connect an image source - -The `CaptureVisionRouter` object, denoted as `cvRouter`, is responsible for handling images provided by an image source. In our scenario, we aim to detect barcodes directly from a live video stream. To facilitate this, we initialize a `CameraEnhancer` object, identified as `cameraEnhancer`, which is specifically designed to capture image frames from the video feed and subsequently forward them to `cvRouter`. - -To enable video streaming on the webpage, we create a `CameraView` object referred to as `cameraView`, which is then passed to `cameraEnhancer`, and its content is displayed on the webpage. - -```html -
-``` - -```javascript -let cameraView = await Dynamsoft.DCE.CameraView.createInstance(); -let cameraEnhancer = await Dynamsoft.DCE.CameraEnhancer.createInstance(cameraView); -document.querySelector("#camera-view-container").append(cameraView.getUIElement()); -cvRouter.setInput(cameraEnhancer); -``` - -#### Register a result receiver - -Once the image processing is complete, the results are sent to all the registered `CapturedResultReceiver` objects. Each `CapturedResultReceiver` object may encompass one or multiple callback functions associated with various result types. In our particular case, our focus is on identifying barcodes within the images, so it's sufficient to define the callback function `onDecodedBarcodesReceived`: - -```javascript -const resultsContainer = document.querySelector("#results"); -const resultReceiver = new Dynamsoft.CVR.CapturedResultReceiver(); -resultReceiver.onDecodedBarcodesReceived = (result) => { - if (result.barcodeResultItems.length > 0) { - resultsContainer.textContent = ''; - for (let item of result.barcodeResultItems) { - // In this example, the barcode result is shown on the page beneath the video - resultsContainer.textContent += `${item.formatString}: ${item.text}\n\n`; - } - } -}; -cvRouter.addResultReceiver(resultReceiver); -``` - -You can also write code like this. It is the same. - -```javascript -const resultsContainer = document.querySelector("#results"); -cvRouter.addResultReceiver({ onDecodedBarcodesReceived: (result) => { - if (result.barcodeResultItems.length > 0) { - resultsContainer.textContent = ''; - for (let item of result.barcodeResultItems) { - // In this example, the barcode result is shown on the page beneath the video - resultsContainer.textContent += `${item.formatString}: ${item.text}\n\n`; - } - } -}}); -``` - -Check out [CapturedResultReceiver](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/capture-vision-router/captured-result-receiver.html) for more information. - -#### Start the process - -With the setup now complete, we can proceed to process the images in two straightforward steps: - -1. Initiate the image source to commence image acquisition. In our scenario, we invoke the `open()` method on `cameraEnhancer` to initiate video streaming and simultaneously initiate the collection of images. These collected images will be dispatched to `cvRouter` as per its request. -2. Define a preset template to commence image processing. In our case, we utilize the "ReadSingleBarcode" template, specifically tailored for processing images containing a single barcode. - -```javascript -await cameraEnhancer.open(); -await cvRouter.startCapturing("ReadSingleBarcode"); -``` - -*Note*: - -* `cvRouter` is engineered to consistently request images from the image source. -* Various preset templates are at your disposal for barcode reading: - -| Template Name | Function Description | -| ------------------------------ | -------------------------------------------------------------- | -| **ReadBarcodes_Default** | Scans a single barcode. | -| **ReadSingleBarcode** | Quickly scans a single barcode. | -| **ReadBarcodes_SpeedFirst** | Prioritizes speed in scanning multiple barcodes. | -| **ReadBarcodes_ReadRateFirst** | Maximizes the number of barcodes read. | -| **ReadBarcodes_Balance** | Balances speed and quantity in reading multiple barcodes. | -| **ReadDenseBarcodes** | Specialized in reading barcodes with high information density. | -| **ReadDistantBarcodes** | Capable of reading barcodes from extended distances. | - -Read more on the [preset CaptureVisionTemplates](./preset-templates.md). - -### Customize the process - -#### Adjust the preset template settings - -When making adjustments to some basic tasks, we often only need to modify [SimplifiedCaptureVisionSettings](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/capture-vision-router/interfaces/simplified-capture-vision-settings.html). - -##### Change barcode settings - -The preset templates can be updated to meet different requirements. For example, the following code limits the barcode format to QR code. - -```javascript -let settings = await cvRouter.getSimplifiedSettings("ReadSingleBarcode"); -settings.barcodeSettings.barcodeFormatIds = - Dynamsoft.DBR.EnumBarcodeFormat.BF_QR_CODE; -await cvRouter.updateSettings("ReadSingleBarcode", settings); -await cvRouter.startCapturing("ReadSingleBarcode"); -``` - -For a list of adjustable barcode settings, check out [SimplifiedBarcodeReaderSettings](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/interfaces/simplified-barcode-reader-settings.html). - -##### Retrieve the original image - -Additionally, we have the option to modify the template to retrieve the original image containing the barcode. - -```javascript -let settings = await cvRouter.getSimplifiedSettings("ReadSingleBarcode"); -settings.capturedResultItemTypes |= - Dynamsoft.Core.EnumCapturedResultItemType.CRIT_ORIGINAL_IMAGE; -await cvRouter.updateSettings("ReadSingleBarcode", settings); -await cvRouter.startCapturing("ReadSingleBarcode"); -``` - -Limit the barcode format to QR code, and retrieve the original image containing the barcode, at the same time. - -```javascript -let settings = await cvRouter.getSimplifiedSettings("ReadSingleBarcode"); -settings.capturedResultItemTypes = - Dynamsoft.DBR.EnumBarcodeFormat.BF_QR_CODE | - Dynamsoft.Core.EnumCapturedResultItemType.CRIT_ORIGINAL_IMAGE; -await cvRouter.updateSettings("ReadSingleBarcode", settings); -await cvRouter.startCapturing("ReadSingleBarcode"); -``` - -Please be aware that it is necessary to update the `CapturedResultReceiver` object to obtain the original image. For instance: - -```javascript -resultReceiver.onCapturedResultReceived = (result) => { - let barcodes = result.items.filter((item) => - item.type === Dynamsoft.Core.EnumCapturedResultItemType.CRIT_BARCODE - ); - if (barcodes.length > 0) { - let image = result.items.filter( - (item) => - item.type === - Dynamsoft.Core.EnumCapturedResultItemType.CRIT_ORIGINAL_IMAGE - )[0].imageData; - // The image that we found the barcode(s) on. - } -}; -``` - -##### Change reading frequency to save power - -The SDK is initially configured to process images sequentially without any breaks. Although this setup maximizes performance, it can lead to elevated power consumption, potentially causing the device to overheat. In many cases, it's possible to reduce the reading speed while still satisfying business requirements. The following code snippet illustrates how to adjust the SDK to process an image every 500 milliseconds: - -> Please bear in mind that in the following code, if an image's processing time is shorter than 500 milliseconds, the SDK will wait for the full 500 milliseconds before proceeding to process the next image. Conversely, if an image's processing time exceeds 500 milliseconds, the subsequent image will be processed immediately upon completion. - -```javascript -let settings = await cvRouter.getSimplifiedSettings("ReadSingleBarcode"); -settings.minImageCaptureInterval = 500; -await cvRouter.updateSettings("ReadSingleBarcode", settings); -await cvRouter.startCapturing("ReadSingleBarcode"); -``` - -##### Specify a scan region - -You can use the parameter `roi` (region of interest) together with the parameter `roiMeasuredInPercentage` to configure the SDK to only read a specific region on the image frames. For example, the following code limits the reading in the center 25%( = 50% * 50%) of the image frames: - -```javascript -let settings = await cvRouter.getSimplifiedSettings("ReadSingleBarcode"); -settings.roiMeasuredInPercentage = true; -settings.roi.points = [ - { x: 25, y: 25 }, - { x: 75, y: 25 }, - { x: 75, y: 75 }, - { x: 25, y: 75 }, -]; -await cvRouter.updateSettings("ReadSingleBarcode", settings); -await cvRouter.startCapturing("ReadSingleBarcode"); -``` - -While the code above accomplishes the task, a more effective approach is to restrict the scan region directly at the image source, as demonstrated in the following code snippet. - -> * With the region configured at the image source, the images are cropped right before they are gathered for processing, eliminating the necessity to modify the processing settings further. -> * `cameraEnhancer` elevates interactivity by overlaying a mask on the video, providing a clear delineation of the scanning region. -> * See also: [CameraEnhancer::setScanRegion](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/acquisition.html#setscanregion) - -```javascript -cameraEnhancer = await Dynamsoft.DCE.CameraEnhancer.createInstance(cameraView); -cameraEnhancer.setScanRegion({ - x: 25, - y: 25, - width: 50, - height: 50, - isMeasuredInPercentage: true, -}); -``` - - - -#### Edit the preset templates directly - -The preset templates have a lot more settings that can be customized to best suit your use case. If you [download the SDK from Dynamsoft website](https://www.dynamsoft.com/barcode-reader/downloads/1000003-confirmation/), you can find the templates under - -* "/dynamsoft-barcode-reader-js-10.0.21/dynamsoft/resources/barcode-reader/templates/" - -Upon completing the template editing, you can invoke the `initSettings` method and provide it with the template path as an argument. - -```javascript -await cvRouter.initSettings("PATH-TO-THE-FILE"); //e.g. "https://your-website/ReadSingleBarcode.json") -await cvRouter.startCapturing("ReadSingleBarcode"); // Make sure the name matches one of the CaptureVisionTemplates in the -``` - -#### Filter the results (Important) - -While processing video frames, it's common for the same barcode to be detected multiple times. To enhance the user experience, we can use [MultiFrameResultCrossFilter](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/utility/multi-frame-result-cross-filter.html) object, having two options currently at our disposal: - -##### Option 1: Verify results across multiple frames - -```js -let filter = new Dynamsoft.Utility.MultiFrameResultCrossFilter(); -filter.enableResultCrossVerification( - Dynamsoft.Core.EnumCapturedResultItemType.CRIT_BARCODE, true -); -await cvRouter.addResultFilter(filter); -``` - -*Note*: - -* `enableResultCrossVerification` was designed to cross-validate the outcomes across various frames in a video streaming scenario, enhancing the reliability of the final results. This validation is particularly crucial for barcodes with limited error correction capabilities, such as 1D codes. - -##### Option 2: Eliminate redundant results detected within a short time frame - -```js -let filter = new Dynamsoft.Utility.MultiFrameResultCrossFilter(); -filter.enableResultDeduplication( - Dynamsoft.Core.EnumCapturedResultItemType.CRIT_BARCODE, true -); -await cvRouter.addResultFilter(filter); -``` - -*Note*: - -* `enableResultDeduplication` was designed to prevent high usage in video streaming scenarios, addressing the repetitive processing of the same code within a short period of time. - -Initially, the filter is set to forget a result 3 seconds after it is first received. During this time frame, if an identical result appears, it is ignored. - -> It's important to know that in version 9.x or earlier, the occurrence of an identical result would reset the timer, thus reinitiating the 3-second count at that point. However, in version 10.0.21 and later, an identical result no longer resets the timer but is instead disregarded, and the duration count continues uninterrupted. - -Under certain circumstances, this duration can be extended with the method `setDuplicateForgetTime()`. - -```js -let filter = new Dynamsoft.Utility.MultiFrameResultCrossFilter(); -filter.setDuplicateForgetTime(5000); // Extend the duration to 5 seconds. -await cvRouter.addResultFilter(filter); -``` - -You can also enable both options at the same time: - -```js -let filter = new Dynamsoft.Utility.MultiFrameResultCrossFilter(); -filter.enableResultCrossVerification( - Dynamsoft.Core.EnumCapturedResultItemType.CRIT_BARCODE, true -); -filter.enableResultDeduplication( - Dynamsoft.Core.EnumCapturedResultItemType.CRIT_BARCODE, true -); -filter.setDuplicateForgetTime(5000); -await cvRouter.addResultFilter(filter); -``` - -#### Add feedback - -When a barcode is detected within the video stream, its position is immediately displayed within the video. Furthermore, utilizing the "Dynamsoft Camera Enhancer" SDK, we can introduce feedback mechanisms, such as emitting a "beep" sound or triggering a "vibration". - -The following code snippet adds a "beep" sound for when a barcode is found: - -```js -const resultReceiver = new Dynamsoft.CVR.CapturedResultReceiver(); -resultReceiver.onDecodedBarcodesReceived = (result) => { - if (result.barcodeResultItems.length > 0) { - Dynamsoft.DCE.Feedback.beep(); - } -}; -cvRouter.addResultReceiver(resultReceiver); -``` - -### Customize the UI - -The UI is part of the auxiliary SDK "Dynamsoft Camera Enhancer", read more on how to [customize the UI](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/user-guide/index.html#customize-the-ui). - -## API Documentation - -You can check out the detailed documentation about the APIs of the SDK at -[https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/?ver=10.0.21](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/?ver=10.0.21). - -## System Requirements - -DBR requires the following features to work: - -- Secure context (HTTPS deployment) - - When deploying your application / website for production, make sure to serve it via a secure HTTPS connection. This is required for two reasons - - - Access to the camera video stream is only granted in a security context. Most browsers impose this restriction. - > Some browsers like Chrome may grant the access for `http://127.0.0.1` and `http://localhost` or even for pages opened directly from the local disk (`file:///...`). This can be helpful for temporary development and test. - - - Dynamsoft License requires a secure context to work. - -- `WebAssembly`, `Blob`, `URL`/`createObjectURL`, `Web Workers` - - The above four features are required for the SDK to work. - -- `MediaDevices`/`getUserMedia` - - This API is required for in-browser video streaming. - -- `getSettings` - - This API inspects the video input which is a `MediaStreamTrack` object about its constrainable properties. - -The following table is a list of supported browsers based on the above requirements: - - | Browser Name | Version | - | :----------: | :--------------: | - | Chrome | v78+1 | - | Firefox | v62+1 | - | Edge | v79+ | - | Safari | v14+ | - - 1 devices running iOS needs to be on iOS 14.3+ for camera video streaming to work in Chrome, Firefox or other Apps using webviews. - -Apart from the browsers, the operating systems may impose some limitations of their own that could restrict the use of the SDK. Browser compatibility ultimately depends on whether the browser on that particular operating system supports the features listed above. - -## How to Upgrade - -If you want to upgrade the SDK from an old version to a newer one, please see [how to upgrade](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/upgrade-guide/index.html?ver=10.0.21&utm_source=guide). - -## Release Notes - -Learn about what are included in each release at [https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/release-notes/index.html](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/release-notes/index.html?ver=10.0.21&utm_source=guide). - -## Next Steps - -Now that you have got the SDK integrated, you can choose to move forward in the following directions - -1. Check out the [Official Samples and Demo](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/index.html?ver=10.0.21) -2. Learn about the [APIs of the SDK](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/index.html?ver=10.0.21) diff --git a/programming/javascript/user-guide/index-v10.2.1000.md b/programming/javascript/user-guide/index-v10.2.1000.md deleted file mode 100644 index ba3fddf6..00000000 --- a/programming/javascript/user-guide/index-v10.2.1000.md +++ /dev/null @@ -1,745 +0,0 @@ ---- -layout: default-layout -title: v10.2.10 User Guide - Dynamsoft Barcode Reader JavaScript Edition -description: This is the user guide of Dynamsoft Barcode Reader JavaScript SDK. -keywords: user guide, javascript, js -breadcrumbText: User Guide -noTitleIndex: true -needGenerateH3Content: true -needAutoGenerateSidebar: true -schema: schemas/dynamsoft-facilitates-mit-research-schema.json ---- - - - -# Barcode Reader for Your Website - User Guide - -[Dynamsoft Barcode Reader JavaScript Edition](https://www.dynamsoft.com/barcode-reader/sdk-javascript/) (DBR-JS) is equipped with industry-leading algorithms for exceptional speed, accuracy and read rates in barcode reading. Using its well-designed API, you can turn your web page into a barcode scanner with just a few lines of code. - -![version](https://img.shields.io/npm/v/dynamsoft-barcode-reader.svg) -![downloads](https://img.shields.io/npm/dm/dynamsoft-barcode-reader.svg) -![jsdelivr](https://img.shields.io/jsdelivr/npm/hm/dynamsoft-barcode-reader.svg) - -![version](https://img.shields.io/npm/v/dynamsoft-javascript-barcode.svg) -![downloads](https://img.shields.io/npm/dm/dynamsoft-javascript-barcode.svg) -![jsdelivr](https://img.shields.io/jsdelivr/npm/hm/dynamsoft-javascript-barcode.svg) - -Once the DBR-JS SDK gets integrated into your web page, your users can access a camera via the browser and read barcodes directly from its video input. - -In this guide, you will learn step by step on how to integrate the DBR-JS SDK into your website. - -Table of Contents - -- [Barcode Reader for Your Website - User Guide](#barcode-reader-for-your-website---user-guide) - - [Hello World - Simplest Implementation](#hello-world---simplest-implementation) - - [Understand the code](#understand-the-code) - - [About the code](#about-the-code) - - [Run the example](#run-the-example) - - [Building your own page](#building-your-own-page) - - [Include the SDK](#include-the-sdk) - - [Use a public CDN](#use-a-public-cdn) - - [Host the SDK yourself (optional)](#host-the-sdk-yourself-optional) - - [Prepare the SDK](#prepare-the-sdk) - - [Specify the license](#specify-the-license) - - [Specify the location of the "engine" files (optional)](#specify-the-location-of-the-engine-files-optional) - - [Set up and start image processing](#set-up-and-start-image-processing) - - [Preload the module](#preload-the-module) - - [Create a CaptureVisionRouter object](#create-a-capturevisionrouter-object) - - [Connect an image source](#connect-an-image-source) - - [Register a result receiver](#register-a-result-receiver) - - [Start the process](#start-the-process) - - [Customize the process](#customize-the-process) - - [Adjust the preset template settings](#adjust-the-preset-template-settings) - - [Change barcode settings](#change-barcode-settings) - - [Retrieve the original image](#retrieve-the-original-image) - - [Change reading frequency to save power](#change-reading-frequency-to-save-power) - - [Specify a scan region](#specify-a-scan-region) - - [Edit the preset templates directly](#edit-the-preset-templates-directly) - - [Filter the results (Important)](#filter-the-results-important) - - [Option 1: Verify results across multiple frames](#option-1-verify-results-across-multiple-frames) - - [Option 2: Eliminate redundant results detected within a short time frame](#option-2-eliminate-redundant-results-detected-within-a-short-time-frame) - - [Add feedback](#add-feedback) - - [Customize the UI](#customize-the-ui) - - [API Documentation](#api-documentation) - - [System Requirements](#system-requirements) - - [How to Upgrade](#how-to-upgrade) - - [Release Notes](#release-notes) - - [Next Steps](#next-steps) - -**Popular Examples** - -- Hello World - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v10.2.10/hello-world/hello-world.html) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/hello-world/hello-world.html?ver=10.2.10&utm_source=guide) -- Angular App - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v10.2.10/hello-world/angular) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/hello-world/angular/dist/dbrjs-sample-angular/browser/?ver=10.2.10&utm_source=guide) -- React App - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v10.2.10/hello-world/react) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/hello-world/react/build/?ver=10.2.10&utm_source=guide) -- Vue App - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v10.2.10/hello-world/vue) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/hello-world/vue/dist/?ver=10.2.10&utm_source=guide) -- PWA App - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v10.2.10/hello-world/pwa) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/hello-world/pwa/helloworld-pwa.html?ver=10.2.10&utm_source=guide) -- WebView in Android and iOS - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/v10.2.10/hello-world/webview) -- Read Driver Licenses - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v10.2.10/use-case/read-a-drivers-license/index.html) \| [Run](https://demo.dynamsoft.com/samples/dbr/js/use-case/read-a-drivers-license/index.html?ver=10.2.10&utm_source=guide) -- Fill A Form - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v10.2.10/use-case/fill-a-form-with-barcode-reading.html) \| [Run](https://demo.dynamsoft.com/samples/dbr/js/use-case/fill-a-form-with-barcode-reading.html?ver=10.2.10&utm_source=guide) -- Show result information on the video - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v10.2.10/use-case/show-result-texts-on-the-video.html) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/use-case/show-result-texts-on-the-video.html?ver=10.2.10&utm_source=guide) -- Debug Camera and Collect Video Frame - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v10.2.10/others/debug) - -You can also: - -- Try the Official Demo - [Run](https://demo.dynamsoft.com/barcode-reader-js/?ver=10.2.10&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-demo/) -- Try Online Examples - [Run](https://demo.dynamsoft.com/Samples/DBR/JS/index.html?ver=10.2.10&utm_source=guide) \| [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/v10.2.10/) - -## Hello World - Simplest Implementation - -Let's start with the "Hello World" example of the DBR-JS SDK which demonstrates how to use the minimum code to enable a web page to read barcodes from a live video stream. - -**Basic Requirements** - - Internet connection - - [A supported browser](#system-requirements) - - Camera access - -### Understand the code - -The complete code of the "Hello World" example is shown below - -```html - - - -
- - - - - -``` - - - -

- - Code in Github - -   - - Run via JSFiddle - -   - - Run in Dynamsoft - -

- ------ - -#### About the code - -- `Dynamsoft.License.LicenseManager.initLicense()`: This method initializes the license for using the SDK in the application. Note that the string "**DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9**" used in this example points to an online license that requires a network connection to work. Read more on [Specify the license](#specify-the-license). - -- `Dynamsoft.Core.CoreModule.loadWasm(["dbr"])`: This is an optional code. Used to load wasm resources in advance, reducing latency between video playing and barcode decoding. - -- `Dynamsoft.CVR.CaptureVisionRouter.createInstance()`: This method creates a `CaptureVisionRouter` object `cvRouter` which controls the entire process in three steps: - - **Retrieve Images from the Image Source** - - `cvRouter` connects to the image source through the [ImageSourceAdapter](https://www.dynamsoft.com/capture-vision/docs/core/architecture/input.html#image-source-adapter?lang=js) interface with the method `setInput()`. - ```js - cvRouter.setInput(cameraEnhancer); - ``` - > The image source in our case is a [CameraEnhancer](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/user-guide/index.html) object created with `Dynamsoft.DCE.CameraEnhancer.createInstance(cameraView)` - - **Coordinate Image-Processing Tasks** - - The coordination happens behind the scenes. `cvRouter` starts the process by specifying a preset template "ReadSingleBarcode" in the method `startCapturing()`. - ```js - cvRouter.startCapturing("ReadSingleBarcode"); - ``` - - **Dispatch Results to Listening Objects** - - The processing results are returned through the [CapturedResultReceiver](https://www.dynamsoft.com/capture-vision/docs/core/architecture/output.html#captured-result-receiver?lang=js) interface. The `CapturedResultReceiver` object is registered to `cvRouter` via the method `addResultReceiver()`. For more information, please check out [Register a result receiver](#register-a-result-receiver). - ```js - cvRouter.addResultReceiver({/*The-CapturedResultReceiver-Object"*/}); - ``` - - Also note that reading from video is extremely fast and there could be many duplicate results. We can use a [filter](#filter-the-results-important) with result deduplication enabled to filter out the duplicate results. The object is registered to `cvRouter` via the method `addResultFilter()`. - ```js - cvRouter.addResultFilter(filter); - ``` - -> Read more on [Capture Vision Router](https://www.dynamsoft.com/capture-vision/docs/core/architecture/#capture-vision-router). - -### Run the example - -You can run the example deployed to [the Dynamsoft Demo Server](https://demo.dynamsoft.com/Samples/DBR/JS/hello-world/hello-world.html?ver=10.2.10&utm_source=guide) or test it with [JSFiddle code editor](https://jsfiddle.net/DynamsoftTeam/csm2f9wb/). - -You will be asked to allow access to your camera, after which the video will be displayed on the page. After that, you can point the camera at a barcode to read it. - -When a barcode is decoded, you will see the result text show up under the video and the barcode location will be highlighted in the video feed. - -Alternatively, you can test locally by copying and pasting the code shown above into a local file (e.g. "hello-world.html") and opening it in your browser. - -*Note*: - -If you open the web page as `file:///` or `http://` , the camera may not work correctly because the [MediaDevices: getUserMedia()](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia) method only works in secure contexts (HTTPS), in some or all supporting browsers. - -To make sure your web application can access the camera, please configure your web server to support HTTPS. The following links may help. - -1. NGINX: [Configuring HTTPS servers](https://nginx.org/en/docs/http/configuring_https_servers.html) -2. IIS: [How to create a Self Signed Certificate in IIS](https://aboutssl.org/how-to-create-a-self-signed-certificate-in-iis/) -3. Tomcat: [Setting Up SSL on Tomcat in 5 minutes](https://dzone.com/articles/setting-ssl-tomcat-5-minutes) -4. Node.js: [npm tls](https://nodejs.org/docs/v0.4.1/api/tls.html) - -If the test doesn't go as expected, you can [contact us](https://www.dynamsoft.com/company/contact/?ver=10.2.10&utm_source=guide&product=dbr&package=js). - -## Building your own page - -### Include the SDK - -To utilize the SDK, the initial step involves including the corresponding resource files: - -* `core.js` encompasses common classes, interfaces, and enumerations shared across all Dynamsoft SDKs. -* `license.js` introduces the `LicenseManager` class, which manages the licensing for all Dynamsoft SDKs. -* `utility.js` encompasses auxiliary classes shared among all Dynamsoft SDKs. -* `dbr.js` defines interfaces and enumerations tailored to the barcode reader module. -* `cvr.js` introduces the `CaptureVisionRouter` class, which governs the entire image processing workflow. -* `dce.js` comprises classes that offer camera support and basic user interface functionalities. - -To simplify things, starting from version 10.0.21, we introduced `dbr.bundle.js`, which combines all six of the above files. In the following chapters, we will use `dbr.bundle.js`. - -#### Use a public CDN - -The simplest way to include the SDK is to use either the [jsDelivr](https://jsdelivr.com/) or [UNPKG](https://unpkg.com/) CDN. The "hello world" example above uses **jsDelivr**. - -- jsDelivr - - ```html - - ``` - -- UNPKG - - ```html - - ``` - -- In some rare cases (such as some restricted areas), you might not be able to access the CDN. If this happens, you can use the following files for the test. - - ```html - - ``` - - However, please **DO NOT** use `download2.dynamsoft.com` resources in a production application as they are for temporary testing purposes only. Instead, you can try hosting the SDK yourself. - -- In frameworks like React and Vue, you may want to add the package as a dependency. - - ```sh - npm i dynamsoft-barcode-reader-bundle@10.2.1000 -E - # or - yarn add dynamsoft-barcode-reader-bundle@10.2.1000 -E - ``` - - NOTE that in frameworks, you need to [specify the engineResourcePaths](#specify-the-location-of-the-engine-files-optional). - -#### Host the SDK yourself (optional) - -Besides using the public CDN, you can also download the SDK and host its files on your own server or a commercial CDN before including it in your application. - -There are two options for downloading the SDK, and the usage for each is slightly different - -- From the website - - [Download Dynamsoft Barcode Reader JavaScript Package](https://www.dynamsoft.com/barcode-reader/downloads/?ver=10.2.10&utm_source=guide&product=dbr&package=js) - - The resources are located at path `dynamsoft/distributables/@`, you can typically include it like this: - - ```html - - ``` - -- npm - - ```sh - npm i dynamsoft-barcode-reader-bundle@10.2.1000 -E - # Compared with using CDN, you need to set up more resources. - npm i dynamsoft-capture-vision-std@1.2.10 -E - npm i dynamsoft-image-processing@2.2.30 -E - ``` - - The resources are located at the path `node_modules/`, without `@`, so the script would be like: - - ```html - - ``` - - Since the version tags (`@`) are missing, you need to [specify the engineResourcePaths](#specify-the-location-of-the-engine-files-optional) so that the SDK can find the resources correctly. - - > To avoid confusion, we suggest renaming "node_modules" or moving "dynamsoft-" packages elsewhere for self-hosting, as "node_modules" is reserved for Node.js dependencies. - -*Note*: - -* Certain legacy web application servers may lack support for the `application/wasm` mimetype for .wasm files. To address this, you have two options: - 1. Upgrade your web application server to one that supports the `application/wasm` mimetype. - 2. Manually define the mimetype on your server. You can refer to the following resources for guidance: - 1. [Apache](https://developer.mozilla.org/en-US/docs/Learn/Server-side/Apache_Configuration_htaccess#media_types_and_character_encodings) - 2. [IIS](https://docs.microsoft.com/en-us/iis/configuration/system.webserver/staticcontent/mimemap) - 3. [Nginx](https://www.nginx.com/resources/wiki/start/topics/examples/full/#mime-types) - -* To work properly, the SDK requires a few engine files, which are relatively large and may take quite a few seconds to download. We recommend that you set a longer cache time for these engine files, to maximize the performance of your web application. - - ```cmd - Cache-Control: max-age=31536000 - ``` - - Reference: [Cache-Control](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control). - -### Prepare the SDK - -Before using the SDK, you need to configure a few things. - -#### Specify the license - -To enable the SDK's functionality, you must provide a valid license. Utilize the API function initLicense to set your license key. - -```javascript -Dynamsoft.License.LicenseManager.initLicense("DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9"); -``` - -As previously stated, the key "DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9" serves as a test license valid for 24 hours, applicable to any newly authorized browser. To test the SDK further, you can request a 30-day free trial license via the Request a Trial License link. - -> Upon registering a Dynamsoft account and obtaining the SDK package from the official website, Dynamsoft will automatically create a 30-day free trial license and embed the corresponding license key into all the provided SDK samples. - -#### Specify the location of the "engine" files (optional) - -This is usually only required with frameworks like Angular or React, etc. where the referenced JavaScript files such as `cvr.js`, `dbr.js` are compiled into another file. - -The purpose is to tell the SDK where to find the engine files (\*.worker.js, \*.wasm.js and \*.wasm, etc.). The API is called `Dynamsoft.Core.CoreModule.engineResourcePaths`: - -```javascript -//The following code uses the jsDelivr CDN, feel free to change it to your own location of these files -Object.assign(Dynamsoft.Core.CoreModule.engineResourcePaths, { - std: "https://cdn.jsdelivr.net/npm/dynamsoft-capture-vision-std@1.2.10/dist/", - dip: "https://cdn.jsdelivr.net/npm/dynamsoft-image-processing@2.2.30/dist/", - core: "https://cdn.jsdelivr.net/npm/dynamsoft-core@3.2.30/dist/", - license: "https://cdn.jsdelivr.net/npm/dynamsoft-license@3.2.21/dist/", - cvr: "https://cdn.jsdelivr.net/npm/dynamsoft-capture-vision-router@2.2.30/dist/", - dbr: "https://cdn.jsdelivr.net/npm/dynamsoft-barcode-reader@10.2.10/dist/", - dce: "https://cdn.jsdelivr.net/npm/dynamsoft-camera-enhancer@4.0.3/dist/" -}); -``` - -### Set up and start image processing - -#### Preload the module - -The image processing logic is encapsulated within .wasm library files, and these files may require some time for downloading. To enhance the speed, we advise utilizing the following method to preload the libraries. - -```js -// Preload the .wasm files -await Dynamsoft.Core.CoreModule.loadWasm(["dbr"]); -``` - -#### Create a CaptureVisionRouter object - -To use the SDK, we first create a `CaptureVisionRouter` object. - -```javascript -Dynamsoft.License.LicenseManager.initLicense("DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9"); - -let cvRouter = null; -try { - cvRouter = await Dynamsoft.CVR.CaptureVisionRouter.createInstance(); -} catch (ex) { - console.error(ex); -} -``` - -*Tip*: - -When creating a `CaptureVisionRouter` object within a function which may be called more than once, it's best to use a "helper" variable to avoid double creation such as `pCvRouter` in the following code: - -```javascript -Dynamsoft.License.LicenseManager.initLicense("DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9"); - -let pCvRouter = null; // The helper variable which is a promise of cvRouter -let cvRouter = null; - -document.getElementById('btn-scan').addEventListener('click', async () => { - try { - cvRouter = await (pCvRouter = pCvRouter || Dynamsoft.CVR.CaptureVisionRouter.createInstance()); - } catch (ex) { - console.error(ex); - } -}); -``` - -#### Connect an image source - -The `CaptureVisionRouter` object, denoted as `cvRouter`, is responsible for handling images provided by an image source. In our scenario, we aim to detect barcodes directly from a live video stream. To facilitate this, we initialize a `CameraEnhancer` object, identified as `cameraEnhancer`, which is specifically designed to capture image frames from the video feed and subsequently forward them to `cvRouter`. - -To enable video streaming on the webpage, we create a `CameraView` object referred to as `cameraView`, which is then passed to `cameraEnhancer`, and its content is displayed on the webpage. - -```html -
-``` - -```javascript -let cameraView = await Dynamsoft.DCE.CameraView.createInstance(); -let cameraEnhancer = await Dynamsoft.DCE.CameraEnhancer.createInstance(cameraView); -document.querySelector("#camera-view-container").append(cameraView.getUIElement()); -cvRouter.setInput(cameraEnhancer); -``` - -#### Register a result receiver - -Once the image processing is complete, the results are sent to all the registered `CapturedResultReceiver` objects. Each `CapturedResultReceiver` object may encompass one or multiple callback functions associated with various result types. In our particular case, our focus is on identifying barcodes within the images, so it's sufficient to define the callback function `onDecodedBarcodesReceived`: - -```javascript -const resultsContainer = document.querySelector("#results"); -const resultReceiver = new Dynamsoft.CVR.CapturedResultReceiver(); -resultReceiver.onDecodedBarcodesReceived = (result) => { - if (result.barcodeResultItems.length > 0) { - resultsContainer.textContent = ''; - for (let item of result.barcodeResultItems) { - // In this example, the barcode results are displayed on the page below the video. - resultsContainer.textContent += `${item.formatString}: ${item.text}\n\n`; - } - } -}; -cvRouter.addResultReceiver(resultReceiver); -``` - -You can also write code like this. It is the same. - -```javascript -const resultsContainer = document.querySelector("#results"); -cvRouter.addResultReceiver({ onDecodedBarcodesReceived: (result) => { - if (result.barcodeResultItems.length > 0) { - resultsContainer.textContent = ''; - for (let item of result.barcodeResultItems) { - // In this example, the barcode results are displayed on the page below the video. - resultsContainer.textContent += `${item.formatString}: ${item.text}\n\n`; - } - } -}}); -``` - -Check out [CapturedResultReceiver](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/capture-vision-router/captured-result-receiver.html) for more information. - -#### Start the process - -With the setup now complete, we can proceed to process the images in two straightforward steps: - -1. Initiate the image source to commence image acquisition. In our scenario, we invoke the `open()` method on `cameraEnhancer` to initiate video streaming and simultaneously initiate the collection of images. These collected images will be dispatched to `cvRouter` as per its request. -2. Define a preset template to commence image processing. In our case, we utilize the "ReadSingleBarcode" template, specifically tailored for processing images containing a single barcode. - -```javascript -await cameraEnhancer.open(); -await cvRouter.startCapturing("ReadSingleBarcode"); -``` - -*Note*: - -* `cvRouter` is engineered to consistently request images from the image source. -* Various preset templates are at your disposal for barcode reading: - -| Template Name | Function Description | -| ------------------------------ | -------------------------------------------------------------- | -| **ReadBarcodes_Default** | Scans a single barcode. | -| **ReadSingleBarcode** | Quickly scans a single barcode. | -| **ReadBarcodes_SpeedFirst** | Prioritizes speed in scanning multiple barcodes. | -| **ReadBarcodes_ReadRateFirst** | Maximizes the number of barcodes read. | -| **ReadBarcodes_Balance** | Balances speed and quantity in reading multiple barcodes. | -| **ReadDenseBarcodes** | Specialized in reading barcodes with high information density. | -| **ReadDistantBarcodes** | Capable of reading barcodes from extended distances. | - -Read more on the [preset CaptureVisionTemplates](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/capture-vision-router/preset-templates.html). - -### Customize the process - -#### Adjust the preset template settings - -When making adjustments to some basic tasks, we often only need to modify [SimplifiedCaptureVisionSettings](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/capture-vision-router/interfaces/simplified-capture-vision-settings.html). - -##### Change barcode settings - -The preset templates can be updated to meet different requirements. For example, the following code limits the barcode format to QR code. - -```javascript -let settings = await cvRouter.getSimplifiedSettings("ReadSingleBarcode"); -settings.barcodeSettings.barcodeFormatIds = - Dynamsoft.DBR.EnumBarcodeFormat.BF_QR_CODE; -await cvRouter.updateSettings("ReadSingleBarcode", settings); -await cvRouter.startCapturing("ReadSingleBarcode"); -``` - -For a list of adjustable barcode settings, check out [SimplifiedBarcodeReaderSettings](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/interfaces/simplified-barcode-reader-settings.html). - -##### Retrieve the original image - -Additionally, we have the option to modify the template to retrieve the original image containing the barcode. - -```javascript -let settings = await cvRouter.getSimplifiedSettings("ReadSingleBarcode"); -settings.capturedResultItemTypes |= - Dynamsoft.Core.EnumCapturedResultItemType.CRIT_ORIGINAL_IMAGE; -await cvRouter.updateSettings("ReadSingleBarcode", settings); -await cvRouter.startCapturing("ReadSingleBarcode"); -``` - -Limit the barcode format to QR code, and retrieve the original image containing the barcode, at the same time. - -```javascript -let settings = await cvRouter.getSimplifiedSettings("ReadSingleBarcode"); -settings.capturedResultItemTypes = - Dynamsoft.DBR.EnumBarcodeFormat.BF_QR_CODE | - Dynamsoft.Core.EnumCapturedResultItemType.CRIT_ORIGINAL_IMAGE; -await cvRouter.updateSettings("ReadSingleBarcode", settings); -await cvRouter.startCapturing("ReadSingleBarcode"); -``` - -Please be aware that it is necessary to update the `CapturedResultReceiver` object to obtain the original image. For instance: - -```javascript -const EnumCRIT = Dynamsoft.Core.EnumCapturedResultItemType; -resultReceiver.onCapturedResultReceived = (result) => { - let barcodes = result.items.filter(item => item.type === EnumCRIT.CRIT_BARCODE); - if (barcodes.length > 0) { - // Use a filter to get the image on which barcodes are found. - let image = result.items.filter( - item => item.type === EnumCRIT.CRIT_ORIGINAL_IMAGE - )[0].imageData; - } -}; -``` - -##### Change reading frequency to save power - -The SDK is initially configured to process images sequentially without any breaks. Although this setup maximizes performance, it can lead to elevated power consumption, potentially causing the device to overheat. In many cases, it's possible to reduce the reading speed while still satisfying business requirements. The following code snippet illustrates how to adjust the SDK to process an image every 500 milliseconds: - -> Please bear in mind that in the following code, if an image's processing time is shorter than 500 milliseconds, the SDK will wait for the full 500 milliseconds before proceeding to process the next image. Conversely, if an image's processing time exceeds 500 milliseconds, the subsequent image will be processed immediately upon completion. - -```javascript -let settings = await cvRouter.getSimplifiedSettings("ReadSingleBarcode"); -settings.minImageCaptureInterval = 500; -await cvRouter.updateSettings("ReadSingleBarcode", settings); -await cvRouter.startCapturing("ReadSingleBarcode"); -``` - -##### Specify a scan region - -We can specify a scan region to allow the SDK to process only part of the image, improving processing speed. The code snippet below demonstrates how to do this using the `cameraEnhancer` image source. - -```javascript -cameraEnhancer = await Dynamsoft.DCE.CameraEnhancer.createInstance(cameraView); -// In this example, we set the scan region to cover the central 25% of the image. -cameraEnhancer.setScanRegion({ - x: 25, - y: 25, - width: 50, - height: 50, - isMeasuredInPercentage: true, -}); -``` - -*Note*: - -1. By configuring the region at the image source, images are cropped before processing, removing the need to adjust any further processing settings. -2. `cameraEnhancer` enhances interactivity by overlaying a mask on the video, clearly marking the scanning region. - -*See Also*: - -[CameraEnhancer::setScanRegion](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/acquisition.html#setscanregion) - - - - - - -#### Edit the preset templates directly - -The preset templates have many more settings that can be customized to suit your use case best. If you [download the SDK from Dynamsoft website](https://www.dynamsoft.com/barcode-reader/downloads/1000003-confirmation/), you can find the templates under - -* "/dynamsoft-barcode-reader-js-10.2.10/dynamsoft/resources/barcode-reader/templates/" - -Upon completing the template editing, you can invoke the `initSettings` method and provide it with the template path as an argument. - -```javascript -await cvRouter.initSettings("PATH-TO-THE-FILE"); // E.g. "https://your-website/ReadSingleBarcode.json") -await cvRouter.startCapturing("ReadSingleBarcode"); // Make sure the name matches one of the CaptureVisionTemplates in the template JSON file. -``` - -#### Filter the results (Important) - -While processing video frames, it's common for the same barcode to be detected multiple times. To enhance the user experience, we can use [MultiFrameResultCrossFilter](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/utility/multi-frame-result-cross-filter.html) object, having two options currently at our disposal: - -##### Option 1: Verify results across multiple frames - -```js -let filter = new Dynamsoft.Utility.MultiFrameResultCrossFilter(); -filter.enableResultCrossVerification("barcode", true); -await cvRouter.addResultFilter(filter); -``` - -*Note*: - -* `enableResultCrossVerification` was designed to cross-validate the outcomes across various frames in a video streaming scenario, enhancing the reliability of the final results. This validation is particularly crucial for barcodes with limited error correction capabilities, such as 1D codes. - -##### Option 2: Eliminate redundant results detected within a short time frame - -```js -let filter = new Dynamsoft.Utility.MultiFrameResultCrossFilter(); -filter.enableResultDeduplication("barcode", true); -await cvRouter.addResultFilter(filter); -``` - -*Note*: - -* `enableResultDeduplication` was designed to prevent high usage in video streaming scenarios, addressing the repetitive processing of the same code within a short period of time. - -Initially, the filter is set to forget a result 3 seconds after it is first received. During this time frame, if an identical result appears, it is ignored. - -> It's important to know that in version 9.x or earlier, the occurrence of an identical result would reset the timer, thus reinitiating the 3-second count at that point. However, in version 10.2.10 and later, an identical result no longer resets the timer but is instead disregarded, and the duration count continues uninterrupted. - -Under certain circumstances, this duration can be extended with the method `setDuplicateForgetTime()`. - -```js -let filter = new Dynamsoft.Utility.MultiFrameResultCrossFilter(); -filter.setDuplicateForgetTime(5000); // Extend the duration to 5 seconds. -await cvRouter.addResultFilter(filter); -``` - -You can also enable both options at the same time: - -```js -let filter = new Dynamsoft.Utility.MultiFrameResultCrossFilter(); -filter.enableResultCrossVerification("barcode", true); -filter.enableResultDeduplication("barcode", true); -filter.setDuplicateForgetTime(5000); -await cvRouter.addResultFilter(filter); -``` - -#### Add feedback - -When a barcode is detected within the video stream, its position is immediately displayed within the video. Furthermore, utilizing the "Dynamsoft Camera Enhancer" SDK, we can introduce feedback mechanisms, such as emitting a "beep" sound or triggering a "vibration". - -The following code snippet adds a "beep" sound for when a barcode is found: - -```js -const resultReceiver = new Dynamsoft.CVR.CapturedResultReceiver(); -resultReceiver.onDecodedBarcodesReceived = (result) => { - if (result.barcodeResultItems.length > 0) { - Dynamsoft.DCE.Feedback.beep(); - } -}; -cvRouter.addResultReceiver(resultReceiver); -``` - -### Customize the UI - -The UI is part of the auxiliary SDK "Dynamsoft Camera Enhancer", read more on how to [customize the UI](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/user-guide/index.html#customize-the-ui). - -## API Documentation - -You can check out the detailed documentation about the APIs of the SDK at -[https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/?ver=10.2.10](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/?ver=10.2.10). - -## System Requirements - -DBR requires the following features to work: - -- Secure context (HTTPS deployment) - - When deploying your application / website for production, make sure to serve it via a secure HTTPS connection. This is required for two reasons - - - Access to the camera video stream is only granted in a security context. Most browsers impose this restriction. - > Some browsers like Chrome may grant the access for `http://127.0.0.1` and `http://localhost` or even for pages opened directly from the local disk (`file:///...`). This can be helpful for temporary development and test. - - - Dynamsoft License requires a secure context to work. - -- `WebAssembly`, `Blob`, `URL`/`createObjectURL`, `Web Workers` - - The above four features are required for the SDK to work. - -- `MediaDevices`/`getUserMedia` - - This API is required for in-browser video streaming. - -- `getSettings` - - This API inspects the video input which is a `MediaStreamTrack` object about its constrainable properties. - -The following table is a list of supported browsers based on the above requirements: - - | Browser Name | Version | - | :----------: | :--------------: | - | Chrome | v78+1 | - | Firefox | v62+1 | - | Edge | v79+ | - | Safari | v14+ | - - 1 devices running iOS needs to be on iOS 14.3+ for camera video streaming to work in Chrome, Firefox or other Apps using webviews. - -Apart from the browsers, the operating systems may impose some limitations of their own that could restrict the use of the SDK. Browser compatibility ultimately depends on whether the browser on that particular operating system supports the features listed above. - -## How to Upgrade - -If you want to upgrade the SDK from an old version to a newer one, please see [how to upgrade](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/upgrade-guide/index.html?ver=10.2.10&utm_source=guide). - -## Release Notes - -Learn about what are included in each release at [https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/release-notes/index.html](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/release-notes/index.html?ver=10.2.10&utm_source=guide). - -## Next Steps - -Now that you have got the SDK integrated, you can choose to move forward in the following directions - -1. Learn how to [Use in Framework](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/user-guide/use-in-framework.html) -2. Check out the [Official Samples and Demo](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/index.html?ver=10.2.10) -3. Learn about the [APIs of the SDK](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/index.html?ver=10.2.10) diff --git a/programming/javascript/user-guide/index-v10.4.2002.md b/programming/javascript/user-guide/index-v10.4.2002.md deleted file mode 100644 index 664038c6..00000000 --- a/programming/javascript/user-guide/index-v10.4.2002.md +++ /dev/null @@ -1,741 +0,0 @@ ---- -layout: default-layout -title: v10.4.20 User Guide - Dynamsoft Barcode Reader JavaScript Edition -description: This is the user guide of Dynamsoft Barcode Reader JavaScript SDK. -keywords: user guide, javascript, js -breadcrumbText: User Guide -noTitleIndex: true -needGenerateH3Content: true -needAutoGenerateSidebar: true -schema: schemas/dynamsoft-facilitates-mit-research-schema.json ---- - - - -# Barcode Reader for Your Website - User Guide - -[Dynamsoft Barcode Reader JavaScript Edition](https://www.dynamsoft.com/barcode-reader/sdk-javascript/) (DBR-JS) is equipped with industry-leading algorithms for exceptional speed, accuracy and read rates in barcode reading. Using its well-designed API, you can turn your web page into a barcode scanner with just a few lines of code. - -![version](https://img.shields.io/npm/v/dynamsoft-barcode-reader.svg) -![downloads](https://img.shields.io/npm/dm/dynamsoft-barcode-reader.svg) -![jsdelivr](https://img.shields.io/jsdelivr/npm/hm/dynamsoft-barcode-reader.svg) - -![version](https://img.shields.io/npm/v/dynamsoft-javascript-barcode.svg) -![downloads](https://img.shields.io/npm/dm/dynamsoft-javascript-barcode.svg) -![jsdelivr](https://img.shields.io/jsdelivr/npm/hm/dynamsoft-javascript-barcode.svg) - -Once the DBR-JS SDK gets integrated into your web page, your users can access a camera via the browser and read barcodes directly from its video input. - -In this guide, you will learn step by step on how to integrate the DBR-JS SDK into your website. - -Table of Contents - -- [Barcode Reader for Your Website - User Guide](#barcode-reader-for-your-website---user-guide) - - [Hello World - Simplest Implementation](#hello-world---simplest-implementation) - - [Understand the code](#understand-the-code) - - [About the code](#about-the-code) - - [Run the example](#run-the-example) - - [Preparing the SDK](#preparing-the-sdk) - - [Step 1: Include the SDK](#step-1-include-the-sdk) - - [Option 1: Use a public CDN](#option-1-use-a-public-cdn) - - [Option 2: Host the SDK yourself (optional)](#option-2-host-the-sdk-yourself-optional) - - [Step 2: Prepare the SDK](#step-2-prepare-the-sdk) - - [1. Specify the license](#1-specify-the-license) - - [2. \[Optional\] Specify the location of the "engine" files](#2-optional-specify-the-location-of-the-engine-files) - - [Using the SDK](#using-the-sdk) - - [Step 1: Preload the module](#step-1-preload-the-module) - - [Step 2: Create a CaptureVisionRouter object](#step-2-create-a-capturevisionrouter-object) - - [Step 3: Connect an image source](#step-3-connect-an-image-source) - - [Step 4: Register a result receiver](#step-4-register-a-result-receiver) - - [Step 5: Start process video frames](#step-5-start-process-video-frames) - - [Customizing the process](#customizing-the-process) - - [1. Adjust the preset template settings](#1-adjust-the-preset-template-settings) - - [1.1. Change barcode settings](#11-change-barcode-settings) - - [1.2. Retrieve the original image](#12-retrieve-the-original-image) - - [1.3. Change reading frequency to save power](#13-change-reading-frequency-to-save-power) - - [1.4. Specify a scan region](#14-specify-a-scan-region) - - [2. Edit the preset templates directly](#2-edit-the-preset-templates-directly) - - [3. \[Important\] Filter the results](#3-important-filter-the-results) - - [Method 1: Verify results across multiple frames](#method-1-verify-results-across-multiple-frames) - - [Method 2: Eliminate redundant results detected within a short time frame](#method-2-eliminate-redundant-results-detected-within-a-short-time-frame) - - [4. Add feedback](#4-add-feedback) - - [Customizing the UI](#customizing-the-ui) - - [Documentation](#documentation) - - [API Reference](#api-reference) - - [How to Upgrade](#how-to-upgrade) - - [Release Notes](#release-notes) - - [Next Steps](#next-steps) - -**Popular Examples** - -- Hello World - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v10.4.30/hello-world/hello-world.html) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/hello-world/hello-world.html?ver=10.4.30&utm_source=guide) -- Angular App - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v10.4.30/hello-world/angular) -- React App - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v10.4.30/hello-world/react) -- Vue App - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v10.4.30/hello-world/vue) -- PWA App - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v10.4.30/hello-world/pwa) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/hello-world/pwa/helloworld-pwa.html?ver=10.4.30&utm_source=guide) -- WebView in Android and iOS - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/v10.4.30/hello-world/webview) -- Read Driver Licenses - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v10.4.30/use-case/read-a-drivers-license/index.html) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/use-case/read-a-drivers-license/index.html?ver=10.4.30&utm_source=guide) -- Fill A Form - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v10.4.30/use-case/fill-a-form-with-barcode-reading.html) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/use-case/fill-a-form-with-barcode-reading.html?ver=10.4.30&utm_source=guide) -- Show result information on the video - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v10.4.30/use-case/show-result-texts-on-the-video.html) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/use-case/show-result-texts-on-the-video.html?ver=10.4.30&utm_source=guide) -- Debug Camera and Collect Video Frame - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v10.4.30/others/debug) - -You can also: - -- Try the Official Demo - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-demo/) \| [Run](https://demo.dynamsoft.com/barcode-reader-js/?ver=10.4.30&utm_source=guide) -- Try Online Examples - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/v10.4.30/) - -## Hello World - Simplest Implementation - -Let's start with the "Hello World" example of the DBR-JS SDK which demonstrates how to use the minimum code to enable a web page to read barcodes from a live video stream. - -**Basic Requirements** - - Internet connection - - A supported browser - - Camera access - -### Understand the code - -The complete code of the "Hello World" example is shown below - -```html - - - -
- - - - - -``` - - - -

- - Code in Github - -   - - Run via JSFiddle - -   - - Run in Dynamsoft - -

- ------ - -#### About the code - -- `Dynamsoft.License.LicenseManager.initLicense()`: This method initializes the license for using the SDK in the application. Note that the string "**DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9**" used in this example points to an online license that requires a network connection to work. Read more on [Specify the license](#specify-the-license). - -- `Dynamsoft.Core.CoreModule.loadWasm(["dbr"])`: This is an optional code. Used to load wasm resources in advance, reducing latency between video playing and barcode decoding. - -- `Dynamsoft.CVR.CaptureVisionRouter.createInstance()`: This method creates a `CaptureVisionRouter` object `cvRouter` which controls the entire process in three steps: - - **Retrieve Images from the Image Source** - - `cvRouter` connects to the image source through the [ImageSourceAdapter](https://www.dynamsoft.com/capture-vision/docs/core/architecture/input.html#image-source-adapter?lang=js) interface with the method `setInput()`. - ```js - cvRouter.setInput(cameraEnhancer); - ``` - > The image source in our case is a [CameraEnhancer](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/user-guide/index.html) object created with `Dynamsoft.DCE.CameraEnhancer.createInstance(cameraView)` - - **Coordinate Image-Processing Tasks** - - The coordination happens behind the scenes. `cvRouter` starts the process by specifying a preset template "ReadSingleBarcode" in the method `startCapturing()`. - ```js - cvRouter.startCapturing("ReadSingleBarcode"); - ``` - - **Dispatch Results to Listening Objects** - - The processing results are returned through the [CapturedResultReceiver](https://www.dynamsoft.com/capture-vision/docs/core/architecture/output.html#captured-result-receiver?lang=js) interface. The `CapturedResultReceiver` object is registered to `cvRouter` via the method `addResultReceiver()`. For more information, please check out [Register a result receiver](#register-a-result-receiver). - ```js - cvRouter.addResultReceiver({/*The-CapturedResultReceiver-Object"*/}); - ``` - - Also note that reading from video is extremely fast and there could be many duplicate results. We can use a [filter](#filter-the-results-important) with result deduplication enabled to filter out the duplicate results. The object is registered to `cvRouter` via the method `addResultFilter()`. - ```js - cvRouter.addResultFilter(filter); - ``` - -> Read more on [Capture Vision Router](https://www.dynamsoft.com/capture-vision/docs/core/architecture/#capture-vision-router). - -### Run the example - -You can run the example deployed to [the Dynamsoft Demo Server](https://demo.dynamsoft.com/Samples/DBR/JS/hello-world/hello-world.html?ver=10.4.30&utm_source=guide) or test it with [JSFiddle code editor](https://jsfiddle.net/DynamsoftTeam/csm2f9wb/). - -You will be asked to allow access to your camera, after which the video will be displayed on the page. After that, you can point the camera at a barcode to read it. - -When a barcode is decoded, you will see the result text show up under the video and the barcode location will be highlighted in the video feed. - -Alternatively, you can test locally by copying and pasting the code shown above into a local file (e.g. "hello-world.html") and opening it in your browser. - -> *Secure Contexts*: -> -> If you open the web page as `http://` , our SDK may not work correctly because the [MediaDevices: getUserMedia()](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia) and other methods only work in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS, `localhost`, `127.0.0.1`, `file://`), in some or all supporting browsers. -> -> Regarding configuring https on your server, these guides for [nginx](https://nginx.org/en/docs/http/configuring_https_servers.html) / [IIS](https://aboutssl.org/how-to-create-a-self-signed-certificate-in-iis/) / [tomcat](https://dzone.com/articles/setting-ssl-tomcat-5-minutes) / [nodejs](https://nodejs.org/docs/v0.4.1/api/tls.html) might help. -> -> If the test doesn't go as expected, you can [contact us](https://www.dynamsoft.com/company/contact/?ver=10.4.20&utm_source=guide&product=dbr&package=js). - -## Preparing the SDK - -### Step 1: Include the SDK - -#### Option 1: Use a public CDN - -The simplest way to include the SDK is to use either the [jsDelivr](https://jsdelivr.com/) or [UNPKG](https://unpkg.com/) CDN. The "hello world" example above uses **jsDelivr**. - -- jsDelivr - - ```html - - ``` - -- UNPKG - - ```html - - ``` - -- In some rare cases (such as some restricted areas), you might not be able to access the CDN. If this happens, you can use the following files for the test. - - ```html - - ``` - - However, please **DO NOT** use `download2.dynamsoft.com` resources in a production application as they are for temporary testing purposes only. Instead, you can try hosting the SDK yourself. - -- In frameworks like React, Vue and Angular, you may want to add the package as a dependency. - - ```sh - npm i dynamsoft-barcode-reader-bundle@10.4.2002 -E - # or - yarn add dynamsoft-barcode-reader-bundle@10.4.2002 -E - ``` - - NOTE that in frameworks, you need to [specify the engineResourcePaths](#specify-the-location-of-the-engine-files-optional). - -#### Option 2: Host the SDK yourself (optional) - -Besides using the public CDN, you can also download the SDK and host its files on your own server or a commercial CDN before including it in your application. - -- From the website - - [Download Dynamsoft Barcode Reader JavaScript Package](https://www.dynamsoft.com/barcode-reader/downloads/?ver=10.4.20&utm_source=guide&product=dbr&package=js) - - The resources are located at path `dynamsoft/distributables/@`. - -- From npm - - ```sh - npm i dynamsoft-barcode-reader-bundle@10.4.2002 -E - # Compared with using CDN, you need to set up more resources. - npm i dynamsoft-capture-vision-std@1.4.10 -E - npm i dynamsoft-image-processing@2.4.20 -E - ``` - - The resources are located at the path `node_modules/`, without `@`. You must copy "dynamsoft-xxx" packages elsewhere and add `@`. The `` can be obtained from `package.json` of each package. Another thing to do is to [specify the engineResourcePaths](#2-optional-specify-the-location-of-the-engine-files) so that the SDK can correctly locate the resources. - > Since "node_modules" is reserved for Node.js dependencies, and in our case the package is used only as static resources, we recommend either renaming the "node_modules" folder or moving the "dynamsoft-" packages to a dedicated folder for static resources in your project to facilitate self-hosting. - -You can typically include SDK like this: - -```html - -``` - -*Note*: - -* Certain legacy web application servers may lack support for the `application/wasm` mimetype for .wasm files. To address this, you have two options: - 1. Upgrade your web application server to one that supports the `application/wasm` mimetype. - 2. Manually define the mimetype on your server. You can refer to the guides for [apache](https://developer.mozilla.org/en-US/docs/Learn/Server-side/Apache_Configuration_htaccess#media_types_and_character_encodings) / [IIS](https://docs.microsoft.com/en-us/iis/configuration/system.webserver/staticcontent/mimemap) / [nginx](https://www.nginx.com/resources/wiki/start/topics/examples/full/#mime-types). - -* To work properly, the SDK requires a few engine files, which are relatively large and may take quite a few seconds to download. We recommend that you set a longer cache time for these engine files, to maximize the performance of your web application. - - ``` - Cache-Control: max-age=31536000 - ``` - - Reference: [Cache-Control](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control). - -### Step 2: Prepare the SDK - -Before using the SDK, you need to configure a few things. - -#### 1. Specify the license - -To enable the SDK's functionality, you must provide a valid license. Utilize the API function initLicense to set your license key. - -```javascript -Dynamsoft.License.LicenseManager.initLicense("DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9"); -``` - -As previously stated, the key "DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9" serves as a test license valid for 24 hours, applicable to any newly authorized browser. To test the SDK further, you can request a 30-day free trial license via the Request a Trial License link. - -> Upon registering a Dynamsoft account and obtaining the SDK package from the official website, Dynamsoft will automatically create a 30-day free trial license and embed the corresponding license key into all the provided SDK samples. - -#### 2. [Optional] Specify the location of the "engine" files - -This is usually only required with frameworks like Angular, React or Vue. - -The purpose is to tell the SDK where to find the engine files (\*.worker.js, \*.wasm.js and \*.wasm, etc.). - -```ts -// in framework -import { CoreModule } from "dynamsoft-barcode-reader-bundle"; -CoreModule.engineResourcePaths.rootDirectory = "https://cdn.jsdelivr.net/npm/"; -``` -```js -// in pure js -Dynamsoft.Core.CoreModule.engineResourcePaths.rootDirectory = "https://cdn.jsdelivr.net/npm/"; -``` -These code uses the jsDelivr CDN as an example, feel free to change it to your own location. - -## Using the SDK - -### Step 1: Preload the module - -The image processing logic is encapsulated within .wasm library files, and these files may require some time for downloading. To enhance the speed, we advise utilizing the following method to preload the libraries. - -```js -// Preload the .wasm files -await Dynamsoft.Core.CoreModule.loadWasm(["dbr"]); -``` - -### Step 2: Create a CaptureVisionRouter object - -To use the SDK, we first create a `CaptureVisionRouter` object. - -```javascript -Dynamsoft.License.LicenseManager.initLicense("DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9"); - -let cvRouter = null; -try { - cvRouter = await Dynamsoft.CVR.CaptureVisionRouter.createInstance(); -} catch (ex) { - console.error(ex); -} -``` - -*Tip*: - -When creating a `CaptureVisionRouter` object within a function which may be called more than once, it's best to use a "helper" variable to avoid double creation such as `pCvRouter` in the following code: - -```javascript -Dynamsoft.License.LicenseManager.initLicense("DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9"); - -let pCvRouter = null; // The helper variable which is a promise of cvRouter -let cvRouter = null; - -document.getElementById('btn-scan').addEventListener('click', async () => { - try { - cvRouter = await (pCvRouter = pCvRouter || Dynamsoft.CVR.CaptureVisionRouter.createInstance()); - } catch (ex) { - console.error(ex); - } -}); -``` - -### Step 3: Connect an image source - -The `CaptureVisionRouter` object, denoted as `cvRouter`, is responsible for handling images provided by an image source. In our scenario, we aim to detect barcodes directly from a live video stream. To facilitate this, we initialize a `CameraEnhancer` object, identified as `cameraEnhancer`, which is specifically designed to capture image frames from the video feed and subsequently forward them to `cvRouter`. - -To enable video streaming on the webpage, we create a `CameraView` object referred to as `cameraView`, which is then passed to `cameraEnhancer`, and its content is displayed on the webpage. - -```html -
-``` - -```javascript -let cameraView = await Dynamsoft.DCE.CameraView.createInstance(); -let cameraEnhancer = await Dynamsoft.DCE.CameraEnhancer.createInstance(cameraView); -document.querySelector("#camera-view-container").append(cameraView.getUIElement()); -cvRouter.setInput(cameraEnhancer); -``` - -### Step 4: Register a result receiver - -Once the image processing is complete, the results are sent to all the registered `CapturedResultReceiver` objects. Each `CapturedResultReceiver` object may encompass one or multiple callback functions associated with various result types. This time we use `onCapturedResultReceived`: - - -```javascript -const resultsContainer = document.querySelector("#results"); -const resultReceiver = new Dynamsoft.CVR.CapturedResultReceiver(); -resultReceiver.onCapturedResultReceived = (result) => { - if (result.barcodeResultItems?.length) { - resultsContainer.textContent = ''; - for (let item of result.barcodeResultItems) { - // In this example, the barcode results are displayed on the page below the video. - resultsContainer.textContent += `${item.formatString}: ${item.text}\n\n`; - } - } -}; -cvRouter.addResultReceiver(resultReceiver); -``` - -You can also write code like this. It is the same. - -```javascript -const resultsContainer = document.querySelector("#results"); -cvRouter.addResultReceiver({ onCapturedResultReceived: (result) => { - if (result.barcodeResultItems?.length) { - resultsContainer.textContent = ''; - for (let item of result.barcodeResultItems) { - // In this example, the barcode results are displayed on the page below the video. - resultsContainer.textContent += `${item.formatString}: ${item.text}\n\n`; - } - } -}}); -``` - -Check out [CapturedResultReceiver](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/capture-vision-router/captured-result-receiver.html) for more information. - -### Step 5: Start process video frames - -With the setup now complete, we can proceed to process the images in two straightforward steps: - -1. Initiate the image source to commence image acquisition. In our scenario, we invoke the `open()` method on `cameraEnhancer` to initiate video streaming and simultaneously initiate the collection of images. These collected images will be dispatched to `cvRouter` as per its request. -2. Define a preset template to commence image processing. In our case, we utilize the "ReadSingleBarcode" template, specifically tailored for processing images containing a single barcode. - -```javascript -await cameraEnhancer.open(); -await cvRouter.startCapturing("ReadSingleBarcode"); -``` - -*Note*: - -* `cvRouter` is engineered to consistently request images from the image source. -* Various preset templates are at your disposal for barcode reading: - -| Template Name | Function Description | -| ------------------------------ | -------------------------------------------------------------- | -| **ReadBarcodes_Default** | Scans multiple barcodes by default setting. | -| **ReadSingleBarcode** | Quickly scans a single barcode. | -| **ReadBarcodes_SpeedFirst** | Prioritizes speed in scanning multiple barcodes. | -| **ReadBarcodes_ReadRateFirst** | Maximizes the number of barcodes read. | -| **ReadBarcodes_Balance** | Balances speed and quantity in reading multiple barcodes. | -| **ReadDenseBarcodes** | Specialized in reading barcodes with high information density. | -| **ReadDistantBarcodes** | Capable of reading barcodes from extended distances. | - -Read more on the [preset CaptureVisionTemplates](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/capture-vision-router/preset-templates.html). - -## Customizing the process - -### 1. Adjust the preset template settings - -When making adjustments to some basic tasks, we often only need to modify [SimplifiedCaptureVisionSettings](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/capture-vision-router/interfaces/simplified-capture-vision-settings.html). - -#### 1.1. Change barcode settings - -The preset templates can be updated to meet different requirements. For example, the following code limits the barcode format to QR code. - -```javascript -let settings = await cvRouter.getSimplifiedSettings("ReadSingleBarcode"); -settings.barcodeSettings.barcodeFormatIds = - Dynamsoft.DBR.EnumBarcodeFormat.BF_QR_CODE; -await cvRouter.updateSettings("ReadSingleBarcode", settings); -await cvRouter.startCapturing("ReadSingleBarcode"); -``` - -For a list of adjustable barcode settings, check out [SimplifiedBarcodeReaderSettings](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/interfaces/simplified-barcode-reader-settings.html). - -#### 1.2. Retrieve the original image - -Additionally, we have the option to modify the template to retrieve the original image containing the barcode. - -```javascript -let settings = await cvRouter.getSimplifiedSettings("ReadSingleBarcode"); -settings.capturedResultItemTypes |= - Dynamsoft.Core.EnumCapturedResultItemType.CRIT_ORIGINAL_IMAGE; -await cvRouter.updateSettings("ReadSingleBarcode", settings); -await cvRouter.startCapturing("ReadSingleBarcode"); -``` - -Limit the barcode format to QR code, and retrieve the original image containing the barcode, at the same time. - -```javascript -let settings = await cvRouter.getSimplifiedSettings("ReadSingleBarcode"); -settings.capturedResultItemTypes = - Dynamsoft.DBR.EnumBarcodeFormat.BF_QR_CODE | - Dynamsoft.Core.EnumCapturedResultItemType.CRIT_ORIGINAL_IMAGE; -await cvRouter.updateSettings("ReadSingleBarcode", settings); -await cvRouter.startCapturing("ReadSingleBarcode"); -``` - -Please be aware that it is necessary to update the `CapturedResultReceiver` object to obtain the original image. For instance: - -```javascript -const EnumCRIT = Dynamsoft.Core.EnumCapturedResultItemType; -resultReceiver.onCapturedResultReceived = (result) => { - if (result.barcodeResultItems?.length) { - // Use a filter to get the image on which barcodes are found. - let image = result.items.filter( - item => item.type === EnumCRIT.CRIT_ORIGINAL_IMAGE - )[0].imageData; - } -}; -``` - -#### 1.3. Change reading frequency to save power - -The SDK is initially configured to process images sequentially without any breaks. Although this setup maximizes performance, it can lead to elevated power consumption, potentially causing the device to overheat. In many cases, it's possible to reduce the reading speed while still satisfying business requirements. The following code snippet illustrates how to adjust the SDK to process an image every 500 milliseconds: - -> Please bear in mind that in the following code, if an image's processing time is shorter than 500 milliseconds, the SDK will wait for the full 500 milliseconds before proceeding to process the next image. Conversely, if an image's processing time exceeds 500 milliseconds, the subsequent image will be processed immediately upon completion. - -```javascript -let settings = await cvRouter.getSimplifiedSettings("ReadSingleBarcode"); -settings.minImageCaptureInterval = 500; -await cvRouter.updateSettings("ReadSingleBarcode", settings); -await cvRouter.startCapturing("ReadSingleBarcode"); -``` - -#### 1.4. Specify a scan region - -We can specify a scan region to allow the SDK to process only part of the image, improving processing speed. The code snippet below demonstrates how to do this using the `cameraEnhancer` image source. - -```javascript -cameraEnhancer = await Dynamsoft.DCE.CameraEnhancer.createInstance(cameraView); -// In this example, we set the scan region to cover the central 25% of the image. -cameraEnhancer.setScanRegion({ - x: 25, - y: 25, - width: 50, - height: 50, - isMeasuredInPercentage: true, -}); -``` - -*Note*: - -1. By configuring the region at the image source, images are cropped before processing, removing the need to adjust any further processing settings. -2. `cameraEnhancer` enhances interactivity by overlaying a mask on the video, clearly marking the scanning region. - -*See Also*: - -[CameraEnhancer::setScanRegion](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/acquisition.html#setscanregion) - - - - - - -### 2. Edit the preset templates directly - -The preset templates have many more settings that can be customized to suit your use case best. If you [download the SDK from Dynamsoft website](https://www.dynamsoft.com/barcode-reader/downloads/1000003-confirmation/), you can find the templates under - -* "/dynamsoft-barcode-reader-js-10.4.2002/dynamsoft/templates/" - -Upon completing the template editing, you can invoke the `initSettings` method and provide it with the template path as an argument. - -```javascript -await cvRouter.initSettings("PATH-TO-THE-FILE"); // E.g. "https://your-website/ReadSingleBarcode.json") -await cvRouter.startCapturing("ReadSingleBarcode"); // Make sure the name matches one of the CaptureVisionTemplates in the template JSON file. -``` - -### 3. [Important] Filter the results - -When processing video frames, the same barcode is often detected multiple times. To improve the user experience, we can use the [MultiFrameResultCrossFilter](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/utility/multi-frame-result-cross-filter.html) object. This object provides two methods for handling duplicate detections, which can be used independently or together, depending on what best suits your application needs: - -#### Method 1: Verify results across multiple frames - -```js -let filter = new Dynamsoft.Utility.MultiFrameResultCrossFilter(); -filter.enableResultCrossVerification("barcode", true); -await cvRouter.addResultFilter(filter); -``` - -*Note*: - -* `enableResultCrossVerification` was designed to cross-validate the outcomes across various frames in a video streaming scenario, enhancing the reliability of the final results. This validation is particularly crucial for barcodes with limited error correction capabilities, such as 1D codes. - -#### Method 2: Eliminate redundant results detected within a short time frame - -```js -let filter = new Dynamsoft.Utility.MultiFrameResultCrossFilter(); -filter.enableResultDeduplication("barcode", true); -await cvRouter.addResultFilter(filter); -``` - -*Note*: - -* `enableResultDeduplication` was designed to prevent high usage in video streaming scenarios, addressing the repetitive processing of the same code within a short period of time. - -Initially, the filter is set to forget a result 3 seconds after it is first received. During this time frame, if an identical result appears, it is ignored. - -> It's important to know that in version 9.x or earlier, the occurrence of an identical result would reset the timer, thus reinitiating the 3-second count at that point. However, in version 10.2.10 and later, an identical result no longer resets the timer but is instead disregarded, and the duration count continues uninterrupted. - -Under certain circumstances, this duration can be extended with the method `setDuplicateForgetTime()`. - -```js -let filter = new Dynamsoft.Utility.MultiFrameResultCrossFilter(); -filter.setDuplicateForgetTime(5000); // Extend the duration to 5 seconds. -await cvRouter.addResultFilter(filter); -``` - -You can also enable both options at the same time: - -```js -let filter = new Dynamsoft.Utility.MultiFrameResultCrossFilter(); -filter.enableResultCrossVerification("barcode", true); -filter.enableResultDeduplication("barcode", true); -filter.setDuplicateForgetTime(5000); -await cvRouter.addResultFilter(filter); -``` - -### 4. Add feedback - -When a barcode is detected within the video stream, its position is immediately displayed within the video. Furthermore, utilizing the "Dynamsoft Camera Enhancer" SDK, we can introduce feedback mechanisms, such as emitting a "beep" sound or triggering a "vibration". - -The following code snippet adds a "beep" sound for when a barcode is found: - -```js -const resultReceiver = new Dynamsoft.CVR.CapturedResultReceiver(); -resultReceiver.onDecodedBarcodesReceived = (result) => { - if (result.barcodeResultItems.length > 0) { - Dynamsoft.DCE.Feedback.beep(); - } -}; -cvRouter.addResultReceiver(resultReceiver); -``` - -## Customizing the UI - -```javascript -// Create a CameraView instance with default settings -let cameraView = await Dynamsoft.DCE.CameraView.createInstance(); -// Create a CameraView instance with a specified HTML file path, typically a local or remote URL -let cameraView1 = await Dynamsoft.DCE.CameraView.createInstance('@engineResourcePath/dce.mobile-native.ui.html'); -// Create a CameraView instance within a specified DOM element -let cameraView2 = await Dynamsoft.DCE.CameraView.createInstance(document.getElementById('my-ui')); -// Create a CameraView instance using a custom UI file path -let cameraView3 = await Dynamsoft.DCE.CameraView.createInstance('url/to/my/ui.html'); - -// Get the UI element associated with the cameraView instance -let uiElement = cameraView.getUIElement(); -// Remove the camera selection dropdown from the CameraView's UI element -uiElement.shadowRoot.querySelector('.dce-sel-camera').remove(); -// Remove the resolution selection dropdown from the CameraView's UI element -uiElement.shadowRoot.querySelector('.dce-sel-resolution').remove(); -``` - -The UI is part of the auxiliary SDK "Dynamsoft Camera Enhancer", read more on how to [customize the UI](https://www.dynamsoft.com/barcode-reader/docs/core/programming/features/ui-customization-js.html?lang=js). - -## Documentation - -### API Reference - -You can check out the detailed documentation about the APIs of the SDK at -[https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/?ver=10.4.2002](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/?ver=10.4.2002). - - - -### How to Upgrade - -If you want to upgrade the SDK from an old version to a newer one, please see [how to upgrade](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/upgrade-guide/index.html?ver=10.4.2002&utm_source=guide). - -### Release Notes - -Learn about what are included in each release at [https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/release-notes/index.html](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/release-notes/index.html?ver=10.4.20&utm_source=guide). - -## Next Steps - -Now that you have got the SDK integrated, you can choose to move forward in the following directions - -1. Learn how to [Use in Framework](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/user-guide/use-in-framework.html) -2. Check out the [Official Samples and Demo](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/index.html?ver=10.4.20) -3. Learn about the [APIs of the SDK](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/index.html?ver=10.4.2002) diff --git a/programming/javascript/user-guide/index-v10.4.3100.md b/programming/javascript/user-guide/index-v10.4.3100.md deleted file mode 100644 index fcbc317b..00000000 --- a/programming/javascript/user-guide/index-v10.4.3100.md +++ /dev/null @@ -1,753 +0,0 @@ ---- -layout: default-layout -title: v10.4.3100 User Guide - Dynamsoft Barcode Reader JavaScript Edition -description: This is the user guide of Dynamsoft Barcode Reader JavaScript SDK. -keywords: user guide, javascript, js -breadcrumbText: User Guide -noTitleIndex: true -needGenerateH3Content: true -needAutoGenerateSidebar: true -schema: schemas/dynamsoft-facilitates-mit-research-schema.json ---- - - - -# Barcode Reader for Your Website - User Guide - -[Dynamsoft Barcode Reader JavaScript Edition](https://www.dynamsoft.com/barcode-reader/sdk-javascript/) (DBR-JS) is equipped with industry-leading algorithms for exceptional speed, accuracy and read rates in barcode reading. Using its well-designed API, you can turn your web page into a barcode scanner with just a few lines of code. - -![version](https://img.shields.io/npm/v/dynamsoft-barcode-reader.svg) -![downloads](https://img.shields.io/npm/dm/dynamsoft-barcode-reader.svg) -![jsdelivr](https://img.shields.io/jsdelivr/npm/hm/dynamsoft-barcode-reader.svg) - -![version](https://img.shields.io/npm/v/dynamsoft-javascript-barcode.svg) -![downloads](https://img.shields.io/npm/dm/dynamsoft-javascript-barcode.svg) -![jsdelivr](https://img.shields.io/jsdelivr/npm/hm/dynamsoft-javascript-barcode.svg) - -Once the DBR-JS SDK gets integrated into your web page, your users can access a camera via the browser and read barcodes directly from its video input. - -In this guide, you will learn step by step on how to integrate the DBR-JS SDK into your website. - -Table of Contents - -- [Barcode Reader for Your Website - User Guide](#barcode-reader-for-your-website---user-guide) - - [Hello World - Simplest Implementation](#hello-world---simplest-implementation) - - [Understand the code](#understand-the-code) - - [About the code](#about-the-code) - - [Run the example](#run-the-example) - - [Preparing the SDK](#preparing-the-sdk) - - [Step 1: Include the SDK](#step-1-include-the-sdk) - - [Step 2: Prepare the SDK](#step-2-prepare-the-sdk) - - [1. Specify the license](#1-specify-the-license) - - [2. \[Optional\] Specify the location of the "engine" files](#2-optional-specify-the-location-of-the-engine-files) - - [Using the SDK](#using-the-sdk) - - [Step 1: Preload the module](#step-1-preload-the-module) - - [Step 2: Create a CaptureVisionRouter object](#step-2-create-a-capturevisionrouter-object) - - [Step 3: Connect an image source](#step-3-connect-an-image-source) - - [Step 4: Register a result receiver](#step-4-register-a-result-receiver) - - [Step 5: Start process video frames](#step-5-start-process-video-frames) - - [Customizing the process](#customizing-the-process) - - [1. Adjust the preset template settings](#1-adjust-the-preset-template-settings) - - [1.1. Change barcode settings](#11-change-barcode-settings) - - [1.2. Retrieve the original image](#12-retrieve-the-original-image) - - [1.3. Change reading frequency to save power](#13-change-reading-frequency-to-save-power) - - [1.4. Specify a scan region](#14-specify-a-scan-region) - - [2. Edit the preset templates directly](#2-edit-the-preset-templates-directly) - - [3. \[Important\] Filter the results](#3-important-filter-the-results) - - [Method 1: Verify results across multiple frames](#method-1-verify-results-across-multiple-frames) - - [Method 2: Eliminate redundant results detected within a short time frame](#method-2-eliminate-redundant-results-detected-within-a-short-time-frame) - - [4. Add feedback](#4-add-feedback) - - [Customizing the UI](#customizing-the-ui) - - [Documentation](#documentation) - - [API Reference](#api-reference) - - [How to Upgrade](#how-to-upgrade) - - [Release Notes](#release-notes) - - [Next Steps](#next-steps) - -**Popular Examples** - -- Hello World - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v10.4.31/hello-world/hello-world.html) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/hello-world/hello-world.html?ver=10.4.31&utm_source=guide) -- Angular App - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v10.4.31/hello-world/angular) -- React App - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v10.4.31/hello-world/react) -- Vue App - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v10.4.31/hello-world/vue) -- PWA App - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v10.4.31/hello-world/pwa) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/hello-world/pwa/helloworld-pwa.html?ver=10.4.31&utm_source=guide) -- WebView in Android and iOS - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/v10.4.31/hello-world/webview) -- Read Driver Licenses - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v10.4.31/use-case/read-a-drivers-license/index.html) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/use-case/read-a-drivers-license/index.html?ver=10.4.31&utm_source=guide) -- Fill A Form - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v10.4.31/use-case/fill-a-form-with-barcode-reading.html) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/use-case/fill-a-form-with-barcode-reading.html?ver=10.4.31&utm_source=guide) -- Show result information on the video - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v10.4.31/use-case/show-result-texts-on-the-video.html) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/use-case/show-result-texts-on-the-video.html?ver=10.4.31&utm_source=guide) -- Debug Camera and Collect Video Frame - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v10.4.31/others/debug) - -You can also: - -- Try the Official Demo - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-demo/) \| [Run](https://demo.dynamsoft.com/barcode-reader-js/?ver=10.4.31&utm_source=guide) -- Try Online Examples - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/v10.4.31/) - -## Hello World - Simplest Implementation - -Let's start with the "Hello World" example of the DBR-JS SDK which demonstrates how to use the minimum code to enable a web page to read barcodes from a live video stream. - -**Basic Requirements** - - - Internet connection - - A supported browser - - Camera access - -> Please refer to [system requirements](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/faq/system-requirement.html) for more details. - -### Understand the code - -The complete code of the "Hello World" example is shown below - -```html - - - -
- - - - - -``` - - - -

- - Code in Github - -   - - Run via JSFiddle - -   - - Run in Dynamsoft - -

- ------ - -#### About the code - -- `Dynamsoft.License.LicenseManager.initLicense()`: This method initializes the license for using the SDK in the application. Note that the string "**DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9**" used in this example points to an online license that requires a network connection to work. Read more on [Specify the license](#1-specify-the-license). - -- `Dynamsoft.Core.CoreModule.loadWasm(["dbr"])`: This is an optional code. Used to load wasm resources in advance, reducing latency between video playing and barcode decoding. - -- `Dynamsoft.CVR.CaptureVisionRouter.createInstance()`: This method creates a `CaptureVisionRouter` object `cvRouter` which controls the entire process in three steps: - - **Retrieve Images from the Image Source** - - `cvRouter` connects to the image source through the [ImageSourceAdapter](https://www.dynamsoft.com/capture-vision/docs/core/architecture/input.html#image-source-adapter?lang=js) interface with the method `setInput()`. - ```js - cvRouter.setInput(cameraEnhancer); - ``` - > The image source in our case is a [CameraEnhancer](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/user-guide/index.html) object created with `Dynamsoft.DCE.CameraEnhancer.createInstance(cameraView)` - - **Coordinate Image-Processing Tasks** - - The coordination happens behind the scenes. `cvRouter` starts the process by specifying a preset template "ReadSingleBarcode" in the method `startCapturing()`. - ```js - cvRouter.startCapturing("ReadSingleBarcode"); - ``` - - **Dispatch Results to Listening Objects** - - The processing results are returned through the [CapturedResultReceiver](https://www.dynamsoft.com/capture-vision/docs/core/architecture/output.html#captured-result-receiver?lang=js) interface. The `CapturedResultReceiver` object is registered to `cvRouter` via the method `addResultReceiver()`. For more information, please check out [Register a result receiver](#step-4-register-a-result-receiver). - ```js - cvRouter.addResultReceiver({/*The-CapturedResultReceiver-Object"*/}); - ``` - - Also note that reading from video is extremely fast and there could be many duplicate results. We can use a [filter](#3-important-filter-the-results) with result deduplication enabled to filter out the duplicate results. The object is registered to `cvRouter` via the method `addResultFilter()`. - ```js - cvRouter.addResultFilter(filter); - ``` - -> Read more on [Capture Vision Router](https://www.dynamsoft.com/capture-vision/docs/core/architecture/#capture-vision-router). - -### Run the example - -You can run the example deployed to [the Dynamsoft Demo Server](https://demo.dynamsoft.com/Samples/DBR/JS/hello-world/hello-world.html?ver=10.4.31&utm_source=guide) or test it with [JSFiddle code editor](https://jsfiddle.net/DynamsoftTeam/csm2f9wb/). - -You will be asked to allow access to your camera, after which the video will be displayed on the page. After that, you can point the camera at a barcode to read it. - -When a barcode is decoded, you will see the result text show up under the video and the barcode location will be highlighted in the video feed. - -Alternatively, you can test locally by copying and pasting the code shown above into a local file (e.g. "hello-world.html") and opening it in your browser. - -> *Secure Contexts*: -> -> If you open the web page as `http://` , our SDK may not work correctly because the [MediaDevices: getUserMedia()](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia) and other methods only work in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS, `localhost`, `127.0.0.1`, `file://`), in some or all supporting browsers. -> -> Regarding configuring https on your server, these guides for [nginx](https://nginx.org/en/docs/http/configuring_https_servers.html) / [IIS](https://aboutssl.org/how-to-create-a-self-signed-certificate-in-iis/) / [tomcat](https://dzone.com/articles/setting-ssl-tomcat-5-minutes) / [nodejs](https://nodejs.org/docs/v0.4.1/api/tls.html) might help. -> -> If the test doesn't go as expected, you can [contact us](https://www.dynamsoft.com/company/contact/?ver=10.4.31&utm_source=guide&product=dbr&package=js). - -## Preparing the SDK - -### Step 1: Include the SDK - -
- - -
-
Use a public CDN
- -The simplest way to include the SDK is to use either the [jsDelivr](https://jsdelivr.com/) or [UNPKG](https://unpkg.com/) CDN. The "hello world" example above uses **jsDelivr**. - -- jsDelivr - - ```html - - ``` - -- UNPKG - - ```html - - ``` - - - -- In frameworks like React, Vue and Angular, you may want to add the package as a dependency. - - ```sh - npm i dynamsoft-barcode-reader-bundle@10.4.3100 -E - # or - yarn add dynamsoft-barcode-reader-bundle@10.4.3100 -E - ``` - - NOTE that in frameworks, you need to [specify the location of the engine files](#2-optional-specify-the-location-of-the-engine-files). -
- -
-
Host the SDK yourself
- -Besides using the public CDN, you can also download the SDK and host its files on your own server or a commercial CDN before including it in your application. - -- From the website - - [Download Dynamsoft Barcode Reader JavaScript Package](https://www.dynamsoft.com/barcode-reader/downloads/?ver=10.4.31&utm_source=guide&product=dbr&package=js) - - The resources are located at path `dynamsoft/distributables/@`. - -- From npm - - ```sh - npm i dynamsoft-barcode-reader-bundle@10.4.3100 -E - # Compared with using CDN, you need to set up more resources. - npm i dynamsoft-capture-vision-std@1.4.21 -E - npm i dynamsoft-image-processing@2.4.31 -E - ``` - - The resources are located at the path `node_modules/`, without `@`. You must copy "dynamsoft-xxx" packages elsewhere and add `@`. The `` can be obtained from `package.json` of each package. Another thing to do is to [specify the engineResourcePaths](#2-optional-specify-the-location-of-the-engine-files) so that the SDK can correctly locate the resources. - > Since "node_modules" is reserved for Node.js dependencies, and in our case the package is used only as static resources, we recommend either renaming the "node_modules" folder or moving the "dynamsoft-" packages to a dedicated folder for static resources in your project to facilitate self-hosting. - -You can typically include SDK like this: - -```html - -``` -
- -
- -*Note*: - -* Certain legacy web application servers may lack support for the `application/wasm` mimetype for .wasm files. To address this, you have two options: - 1. Upgrade your web application server to one that supports the `application/wasm` mimetype. - 2. Manually define the mimetype on your server. You can refer to the guides for [apache](https://developer.mozilla.org/en-US/docs/Learn/Server-side/Apache_Configuration_htaccess#media_types_and_character_encodings) / [IIS](https://docs.microsoft.com/en-us/iis/configuration/system.webserver/staticcontent/mimemap) / [nginx](https://www.nginx.com/resources/wiki/start/topics/examples/full/#mime-types). - -* To work properly, the SDK requires a few engine files, which are relatively large and may take quite a few seconds to download. We recommend that you set a longer cache time for these engine files, to maximize the performance of your web application. - - ``` - Cache-Control: max-age=31536000 - ``` - - Reference: [Cache-Control](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control). - -### Step 2: Prepare the SDK - -Before using the SDK, you need to configure a few things. - -#### 1. Specify the license - -To enable the SDK's functionality, you must provide a valid license. Utilize the API function initLicense to set your license key. - -```javascript -Dynamsoft.License.LicenseManager.initLicense("DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9"); -``` - -As previously stated, the key "DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9" serves as a test license valid for 24 hours, applicable to any newly authorized browser. To test the SDK further, you can request a 30-day free trial license via the Request a Trial License link. - -> Upon registering a Dynamsoft account and obtaining the SDK package from the official website, Dynamsoft will automatically create a 30-day free trial license and embed the corresponding license key into all the provided SDK samples. - -#### 2. [Optional] Specify the location of the "engine" files - -This is usually only required with frameworks like Angular, React or Vue. - -The purpose is to tell the SDK where to find the engine files (\*.worker.js, \*.wasm.js and \*.wasm, etc.). - -```ts -// in framework -import { CoreModule } from "dynamsoft-barcode-reader-bundle"; -CoreModule.engineResourcePaths.rootDirectory = "https://cdn.jsdelivr.net/npm/"; -``` -```js -// in pure js -Dynamsoft.Core.CoreModule.engineResourcePaths.rootDirectory = "https://cdn.jsdelivr.net/npm/"; -``` -These code uses the jsDelivr CDN as an example, feel free to change it to your own location. - -## Using the SDK - -### Step 1: Preload the module - -The image processing logic is encapsulated within .wasm library files, and these files may require some time for downloading. To enhance the speed, we advise utilizing the following method to preload the libraries. - -```js -// Preload the .wasm files -await Dynamsoft.Core.CoreModule.loadWasm(["dbr"]); -``` - -### Step 2: Create a CaptureVisionRouter object - -To use the SDK, we first create a `CaptureVisionRouter` object. - -```javascript -Dynamsoft.License.LicenseManager.initLicense("DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9"); - -let cvRouter = null; -try { - cvRouter = await Dynamsoft.CVR.CaptureVisionRouter.createInstance(); -} catch (ex) { - console.error(ex); -} -``` - -*Tip*: - -When creating a `CaptureVisionRouter` object within a function which may be called more than once, it's best to use a "helper" variable to avoid double creation such as `pCvRouter` in the following code: - -```javascript -Dynamsoft.License.LicenseManager.initLicense("DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9"); - -let pCvRouter = null; // The helper variable which is a promise of cvRouter -let cvRouter = null; - -document.getElementById('btn-scan').addEventListener('click', async () => { - try { - cvRouter = await (pCvRouter = pCvRouter || Dynamsoft.CVR.CaptureVisionRouter.createInstance()); - } catch (ex) { - console.error(ex); - } -}); -``` - -### Step 3: Connect an image source - -The `CaptureVisionRouter` object, denoted as `cvRouter`, is responsible for handling images provided by an image source. In our scenario, we aim to detect barcodes directly from a live video stream. To facilitate this, we initialize a `CameraEnhancer` object, identified as `cameraEnhancer`, which is specifically designed to capture image frames from the video feed and subsequently forward them to `cvRouter`. - -To enable video streaming on the webpage, we create a `CameraView` object referred to as `cameraView`, which is then passed to `cameraEnhancer`, and its content is displayed on the webpage. - -```html -
-``` - -```javascript -let cameraView = await Dynamsoft.DCE.CameraView.createInstance(); -let cameraEnhancer = await Dynamsoft.DCE.CameraEnhancer.createInstance(cameraView); -document.querySelector("#camera-view-container").append(cameraView.getUIElement()); -cvRouter.setInput(cameraEnhancer); -``` - -### Step 4: Register a result receiver - -Once the image processing is complete, the results are sent to all the registered `CapturedResultReceiver` objects. Each `CapturedResultReceiver` object may encompass one or multiple callback functions associated with various result types. This time we use `onCapturedResultReceived`: - - -```javascript -const resultsContainer = document.querySelector("#results"); -const resultReceiver = new Dynamsoft.CVR.CapturedResultReceiver(); -resultReceiver.onCapturedResultReceived = (result) => { - if (result.barcodeResultItems?.length) { - resultsContainer.textContent = ''; - for (let item of result.barcodeResultItems) { - // In this example, the barcode results are displayed on the page below the video. - resultsContainer.textContent += `${item.formatString}: ${item.text}\n\n`; - } - } -}; -cvRouter.addResultReceiver(resultReceiver); -``` - -You can also write code like this. It is the same. - -```javascript -const resultsContainer = document.querySelector("#results"); -cvRouter.addResultReceiver({ onCapturedResultReceived: (result) => { - if (result.barcodeResultItems?.length) { - resultsContainer.textContent = ''; - for (let item of result.barcodeResultItems) { - // In this example, the barcode results are displayed on the page below the video. - resultsContainer.textContent += `${item.formatString}: ${item.text}\n\n`; - } - } -}}); -``` - -Check out [CapturedResultReceiver](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/capture-vision-router/captured-result-receiver.html) for more information. - -### Step 5: Start process video frames - -With the setup now complete, we can proceed to process the images in two straightforward steps: - -1. Initiate the image source to commence image acquisition. In our scenario, we invoke the `open()` method on `cameraEnhancer` to initiate video streaming and simultaneously initiate the collection of images. These collected images will be dispatched to `cvRouter` as per its request. -2. Define a preset template to commence image processing. In our case, we utilize the "ReadSingleBarcode" template, specifically tailored for processing images containing a single barcode. - -```javascript -await cameraEnhancer.open(); -await cvRouter.startCapturing("ReadSingleBarcode"); -``` - -*Note*: - -* `cvRouter` is engineered to consistently request images from the image source. -* Various preset templates are at your disposal for barcode reading: - -| Template Name | Function Description | -| ------------------------------ | -------------------------------------------------------------- | -| **ReadBarcodes_Default** | Scans multiple barcodes by default setting. | -| **ReadSingleBarcode** | Quickly scans a single barcode. | -| **ReadBarcodes_SpeedFirst** | Prioritizes speed in scanning multiple barcodes. | -| **ReadBarcodes_ReadRateFirst** | Maximizes the number of barcodes read. | -| **ReadBarcodes_Balance** | Balances speed and quantity in reading multiple barcodes. | -| **ReadDenseBarcodes** | Specialized in reading barcodes with high information density. | -| **ReadDistantBarcodes** | Capable of reading barcodes from extended distances. | - -Read more on the [preset CaptureVisionTemplates](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/capture-vision-router/preset-templates.html). - -## Customizing the process - -### 1. Adjust the preset template settings - -When making adjustments to some basic tasks, we often only need to modify [SimplifiedCaptureVisionSettings](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/capture-vision-router/interfaces/simplified-capture-vision-settings.html). - -#### 1.1. Change barcode settings - -The preset templates can be updated to meet different requirements. For example, the following code limits the barcode format to QR code. - -```javascript -let settings = await cvRouter.getSimplifiedSettings("ReadSingleBarcode"); -settings.barcodeSettings.barcodeFormatIds = - Dynamsoft.DBR.EnumBarcodeFormat.BF_QR_CODE; -await cvRouter.updateSettings("ReadSingleBarcode", settings); -await cvRouter.startCapturing("ReadSingleBarcode"); -``` - -For a list of adjustable barcode settings, check out [SimplifiedBarcodeReaderSettings](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/interfaces/simplified-barcode-reader-settings.html) and [EnumBarcodeFormat](https://www.dynamsoft.com/capture-vision/docs/core/enums/barcode-reader/barcode-format.html?lang=js&product=dbr). - -#### 1.2. Retrieve the original image - -Additionally, we have the option to modify the template to retrieve the original image containing the barcode. - -```javascript -let settings = await cvRouter.getSimplifiedSettings("ReadSingleBarcode"); -settings.capturedResultItemTypes |= - Dynamsoft.Core.EnumCapturedResultItemType.CRIT_ORIGINAL_IMAGE; -await cvRouter.updateSettings("ReadSingleBarcode", settings); -await cvRouter.startCapturing("ReadSingleBarcode"); -``` - -Limit the barcode format to QR code, and retrieve the original image containing the barcode, at the same time. - -```javascript -let settings = await cvRouter.getSimplifiedSettings("ReadSingleBarcode"); -settings.capturedResultItemTypes = - Dynamsoft.DBR.EnumBarcodeFormat.BF_QR_CODE | - Dynamsoft.Core.EnumCapturedResultItemType.CRIT_ORIGINAL_IMAGE; -await cvRouter.updateSettings("ReadSingleBarcode", settings); -await cvRouter.startCapturing("ReadSingleBarcode"); -``` - -Please be aware that it is necessary to update the `CapturedResultReceiver` object to obtain the original image. For instance: - -```javascript -const EnumCRIT = Dynamsoft.Core.EnumCapturedResultItemType; -resultReceiver.onCapturedResultReceived = (result) => { - if (result.barcodeResultItems?.length) { - // Use a filter to get the image on which barcodes are found. - let image = result.items.filter( - item => item.type === EnumCRIT.CRIT_ORIGINAL_IMAGE - )[0].imageData; - } -}; -``` - -#### 1.3. Change reading frequency to save power - -The SDK is initially configured to process images sequentially without any breaks. Although this setup maximizes performance, it can lead to elevated power consumption, potentially causing the device to overheat. In many cases, it's possible to reduce the reading speed while still satisfying business requirements. The following code snippet illustrates how to adjust the SDK to process an image every 500 milliseconds: - -> Please bear in mind that in the following code, if an image's processing time is shorter than 500 milliseconds, the SDK will wait for the full 500 milliseconds before proceeding to process the next image. Conversely, if an image's processing time exceeds 500 milliseconds, the subsequent image will be processed immediately upon completion. - -```javascript -let settings = await cvRouter.getSimplifiedSettings("ReadSingleBarcode"); -settings.minImageCaptureInterval = 500; -await cvRouter.updateSettings("ReadSingleBarcode", settings); -await cvRouter.startCapturing("ReadSingleBarcode"); -``` - -#### 1.4. Specify a scan region - -We can specify a scan region to allow the SDK to process only part of the image, improving processing speed. The code snippet below demonstrates how to do this using the `cameraEnhancer` image source. - -```javascript -cameraEnhancer = await Dynamsoft.DCE.CameraEnhancer.createInstance(cameraView); -// In this example, we set the scan region to cover the central 25% of the image. -cameraEnhancer.setScanRegion({ - x: 25, - y: 25, - width: 50, - height: 50, - isMeasuredInPercentage: true, -}); -``` - -*Note*: - -1. By configuring the region at the image source, images are cropped before processing, removing the need to adjust any further processing settings. -2. `cameraEnhancer` enhances interactivity by overlaying a mask on the video, clearly marking the scanning region. - -*See Also*: - -[CameraEnhancer::setScanRegion](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/acquisition.html#setscanregion) - - - - - - -### 2. Edit the preset templates directly - -The preset templates have many more settings that can be customized to suit your use case best. If you [download the SDK from Dynamsoft website](https://www.dynamsoft.com/barcode-reader/downloads/1000003-confirmation/), you can find the templates under - -* "/dynamsoft-barcode-reader-js-10.4.3100/dynamsoft/templates/" - -Upon completing the template editing, you can invoke the `initSettings` method and provide it with the template path as an argument. - -```javascript -await cvRouter.initSettings("PATH-TO-THE-FILE"); // E.g. "https://your-website/ReadSingleBarcode.json") -await cvRouter.startCapturing("ReadSingleBarcode"); // Make sure the name matches one of the CaptureVisionTemplates in the template JSON file. -``` - -### 3. [Important] Filter the results - -When processing video frames, the same barcode is often detected multiple times. To improve the user experience, we can use the [MultiFrameResultCrossFilter](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/utility/multi-frame-result-cross-filter.html) object. This object provides two methods for handling duplicate detections, which can be used independently or together, depending on what best suits your application needs: - -#### Method 1: Verify results across multiple frames - -```js -let filter = new Dynamsoft.Utility.MultiFrameResultCrossFilter(); -filter.enableResultCrossVerification("barcode", true); -await cvRouter.addResultFilter(filter); -``` - -*Note*: - -* `enableResultCrossVerification` was designed to cross-validate the outcomes across various frames in a video streaming scenario, enhancing the reliability of the final results. This validation is particularly crucial for barcodes with limited error correction capabilities, such as 1D codes. - -#### Method 2: Eliminate redundant results detected within a short time frame - -```js -let filter = new Dynamsoft.Utility.MultiFrameResultCrossFilter(); -filter.enableResultDeduplication("barcode", true); -await cvRouter.addResultFilter(filter); -``` - -*Note*: - -* `enableResultDeduplication` was designed to prevent high usage in video streaming scenarios, addressing the repetitive processing of the same code within a short period of time. - -Initially, the filter is set to forget a result 3 seconds after it is first received. During this time frame, if an identical result appears, it is ignored. - -> It's important to know that in version 9.x or earlier, the occurrence of an identical result would reset the timer, thus reinitiating the 3-second count at that point. However, in version 10.2.10 and later, an identical result no longer resets the timer but is instead disregarded, and the duration count continues uninterrupted. - -Under certain circumstances, this duration can be extended with the method `setDuplicateForgetTime()`. - -```js -let filter = new Dynamsoft.Utility.MultiFrameResultCrossFilter(); -filter.setDuplicateForgetTime(5000); // Extend the duration to 5 seconds. -await cvRouter.addResultFilter(filter); -``` - -You can also enable both options at the same time: - -```js -let filter = new Dynamsoft.Utility.MultiFrameResultCrossFilter(); -filter.enableResultCrossVerification("barcode", true); -filter.enableResultDeduplication("barcode", true); -filter.setDuplicateForgetTime(5000); -await cvRouter.addResultFilter(filter); -``` - -### 4. Add feedback - -When a barcode is detected within the video stream, its position is immediately displayed within the video. Furthermore, utilizing the "Dynamsoft Camera Enhancer" SDK, we can introduce feedback mechanisms, such as emitting a "beep" sound or triggering a "vibration". - -The following code snippet adds a "beep" sound for when a barcode is found: - -```js -const resultReceiver = new Dynamsoft.CVR.CapturedResultReceiver(); -resultReceiver.onDecodedBarcodesReceived = (result) => { - if (result.barcodeResultItems.length > 0) { - Dynamsoft.DCE.Feedback.beep(); - } -}; -cvRouter.addResultReceiver(resultReceiver); -``` - -## Customizing the UI - -```javascript -// Create a CameraView instance with default settings -let cameraView = await Dynamsoft.DCE.CameraView.createInstance(); -// Create a CameraView instance with a specified HTML file path, typically a local or remote URL -let cameraView1 = await Dynamsoft.DCE.CameraView.createInstance('@engineResourcePath/dce.mobile-native.ui.html'); -// Create a CameraView instance within a specified DOM element -let cameraView2 = await Dynamsoft.DCE.CameraView.createInstance(document.getElementById('my-ui')); -// Create a CameraView instance using a custom UI file path -let cameraView3 = await Dynamsoft.DCE.CameraView.createInstance('url/to/my/ui.html'); - -// Get the UI element associated with the cameraView instance -let uiElement = cameraView.getUIElement(); -// Remove the camera selection dropdown from the CameraView's UI element -uiElement.shadowRoot.querySelector('.dce-sel-camera').remove(); -// Remove the resolution selection dropdown from the CameraView's UI element -uiElement.shadowRoot.querySelector('.dce-sel-resolution').remove(); -``` - -The UI is part of the auxiliary SDK "Dynamsoft Camera Enhancer", read more on how to [customize the UI](https://www.dynamsoft.com/barcode-reader/docs/core/programming/features/ui-customization-js.html?lang=js). - -## Documentation - -### API Reference - -You can check out the detailed documentation about the APIs of the SDK at -[https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/?ver=10.4.3100](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/?ver=10.4.3100). - - - -### How to Upgrade - -If you want to upgrade the SDK from an old version to a newer one, please see [how to upgrade](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/upgrade-guide/index.html?ver=10.4.3100&utm_source=guide). - -### Release Notes - -Learn about what are included in each release at [https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/release-notes/index.html](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/release-notes/index.html?ver=10.4.31&utm_source=guide). - -## Next Steps - -Now that you have got the SDK integrated, you can choose to move forward in the following directions - -1. Learn how to [Use in Framework](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/user-guide/use-in-framework.html) -2. Check out the [Official Samples and Demo](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/index.html?ver=10.4.31) -3. Learn about the [APIs of the SDK](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/index.html?ver=10.4.3100) diff --git a/programming/javascript/user-guide/index-v10.5.3000.md b/programming/javascript/user-guide/index-v10.5.3000.md deleted file mode 100644 index 985f186c..00000000 --- a/programming/javascript/user-guide/index-v10.5.3000.md +++ /dev/null @@ -1,759 +0,0 @@ ---- -layout: default-layout -title: v10.5.3000 User Guide - Dynamsoft Barcode Reader JavaScript Edition -description: This is the user guide of Dynamsoft Barcode Reader JavaScript SDK. -keywords: user guide, javascript, js -breadcrumbText: User Guide -noTitleIndex: true -needGenerateH3Content: true -needAutoGenerateSidebar: true -schema: schemas/dynamsoft-facilitates-mit-research-schema.json ---- - - - -# Barcode Reader for Your Website - User Guide - -[Dynamsoft Barcode Reader JavaScript Edition](https://www.dynamsoft.com/barcode-reader/sdk-javascript/) (DBR-JS) is equipped with industry-leading algorithms for exceptional speed, accuracy and read rates in barcode reading. Using its well-designed API, you can turn your web page into a barcode scanner with just a few lines of code. - - - -Once the DBR-JS SDK gets integrated into your web page, your users can access a camera via the browser and read barcodes directly from its video input. - -In this guide, you will learn step by step on how to integrate the DBR-JS SDK into your website. - -Table of Contents - -- [Barcode Reader for Your Website - User Guide](#barcode-reader-for-your-website---user-guide) - - [Hello World - Simplest Implementation](#hello-world---simplest-implementation) - - [Understand the code](#understand-the-code) - - [About the code](#about-the-code) - - [Run the example](#run-the-example) - - [Preparing the SDK](#preparing-the-sdk) - - [Step 1: Include the SDK](#step-1-include-the-sdk) - - [Step 2: Prepare the SDK](#step-2-prepare-the-sdk) - - [1. Specify the license](#1-specify-the-license) - - [2. \[Optional\] Specify the location of the "engine" files](#2-optional-specify-the-location-of-the-engine-files) - - [Using the SDK](#using-the-sdk) - - [Step 1: Preload the module](#step-1-preload-the-module) - - [Step 2: Create a CaptureVisionRouter object](#step-2-create-a-capturevisionrouter-object) - - [Step 3: Connect an image source](#step-3-connect-an-image-source) - - [Step 4: Register a result receiver](#step-4-register-a-result-receiver) - - [Step 5: Start process video frames](#step-5-start-process-video-frames) - - [Customizing the process](#customizing-the-process) - - [1. Adjust the preset template settings](#1-adjust-the-preset-template-settings) - - [1.1. Change barcode settings](#11-change-barcode-settings) - - [1.2. Retrieve the original image](#12-retrieve-the-original-image) - - [1.3. Change reading frequency to save power](#13-change-reading-frequency-to-save-power) - - [1.4. Specify a scan region](#14-specify-a-scan-region) - - [2. Edit the preset templates directly](#2-edit-the-preset-templates-directly) - - [3. \[Important\] Filter the results](#3-important-filter-the-results) - - [Method 1: Verify results across multiple frames](#method-1-verify-results-across-multiple-frames) - - [Method 2: Eliminate redundant results detected within a short time frame](#method-2-eliminate-redundant-results-detected-within-a-short-time-frame) - - [4. Add feedback](#4-add-feedback) - - [Customizing the UI](#customizing-the-ui) - - [Documentation](#documentation) - - [API Reference](#api-reference) - - [How to Upgrade](#how-to-upgrade) - - [Release Notes](#release-notes) - - [Next Steps](#next-steps) - -**Popular Examples** - -- Hello World - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v10.5.30/foundational-api-samples/hello-world/hello-world.html) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/foundational-api-samples/hello-world/hello-world.html?ver=10.5.30&utm_source=guide) -- Angular App - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v10.5.30/foundational-api-samples/hello-world/angular) -- React App - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v10.5.30/foundational-api-samples/hello-world/react) -- Vue App - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v10.5.30/foundational-api-samples/hello-world/vue) -- PWA App - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v10.5.30/foundational-api-samples/hello-world/pwa) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/foundational-api-samples/hello-world/pwa/helloworld-pwa.html?ver=10.5.30&utm_source=guide) -- WebView in Android and iOS - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/v10.5.30/foundational-api-samples/hello-world/webview) -- Read Driver Licenses - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v10.5.30/foundational-api-samples/use-case/read-a-drivers-license/index.html) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/foundational-api-samples/use-case/read-a-drivers-license/index.html?ver=10.5.30&utm_source=guide) -- Fill A Form - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v10.5.30/foundational-api-samples/use-case/fill-a-form-with-barcode-reading.html) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/foundational-api-samples/use-case/fill-a-form-with-barcode-reading.html?ver=10.5.30&utm_source=guide) -- Show result information on the video - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v10.5.30/foundational-api-samples/use-case/show-result-texts-on-the-video.html) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/foundational-api-samples/use-case/show-result-texts-on-the-video.html?ver=10.5.30&utm_source=guide) -- Debug Camera and Collect Video Frame - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v10.5.30/foundational-api-samples/others/debug) - -You can also: - -- Try the Official Demo - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-demo/) \| [Run](https://demo.dynamsoft.com/barcode-reader-js/?ver=10.5.30&utm_source=guide) -- Try Online Examples - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/v10.5.30/) - -## Hello World - Simplest Implementation - -Let's start with the "Hello World" example of the DBR-JS SDK which demonstrates how to use the minimum code to enable a web page to read barcodes from a live video stream. - -**Basic Requirements** - - - Internet connection - - A supported browser - - Camera access - -> Please refer to [system requirements](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/faq/system-requirement.html) for more details. - -### Understand the code - -The complete code of the "Hello World" example is shown below - -```html - - - -
- - - - - -``` - - - -

- - Code in Github - -   - - Run via JSFiddle - -   - - Run in Dynamsoft - -

- -> Don't want to deal with too many details? You can get a quick start with the [BarcodeScanner >>](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/user-guide/barcode-scanner.html) -> ```js -> // Scan instantly with a single line of code! -> new Dynamsoft.BarcodeScanner().launch().then(result=>alert(result.barcodeResults[0].text)); -> ``` - ------ - -#### About the code - -- `Dynamsoft.License.LicenseManager.initLicense()`: This method initializes the license for using the SDK in the application. Note that the string "**DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9**" used in this example points to an online license that requires a network connection to work. Read more on [Specify the license](#1-specify-the-license). - -- `Dynamsoft.Core.CoreModule.loadWasm(["dbr"])`: This is an optional code. Used to load wasm resources in advance, reducing latency between video playing and barcode decoding. - -- `Dynamsoft.CVR.CaptureVisionRouter.createInstance()`: This method creates a `CaptureVisionRouter` object `cvRouter` which controls the entire process in three steps: - - **Retrieve Images from the Image Source** - - `cvRouter` connects to the image source through the [ImageSourceAdapter](https://www.dynamsoft.com/capture-vision/docs/core/architecture/input.html#image-source-adapter?lang=js) interface with the method `setInput()`. - ```js - cvRouter.setInput(cameraEnhancer); - ``` - > The image source in our case is a [CameraEnhancer](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/user-guide/index.html) object created with `Dynamsoft.DCE.CameraEnhancer.createInstance(cameraView)` - - **Coordinate Image-Processing Tasks** - - The coordination happens behind the scenes. `cvRouter` starts the process by specifying a preset template "ReadSingleBarcode" in the method `startCapturing()`. - ```js - cvRouter.startCapturing("ReadSingleBarcode"); - ``` - - **Dispatch Results to Listening Objects** - - The processing results are returned through the [CapturedResultReceiver](https://www.dynamsoft.com/capture-vision/docs/core/architecture/output.html#captured-result-receiver?lang=js) interface. The `CapturedResultReceiver` object is registered to `cvRouter` via the method `addResultReceiver()`. For more information, please check out [Register a result receiver](#step-4-register-a-result-receiver). - ```js - cvRouter.addResultReceiver({/*The-CapturedResultReceiver-Object"*/}); - ``` - - Also note that reading from video is extremely fast and there could be many duplicate results. We can use a [filter](#3-important-filter-the-results) with result deduplication enabled to filter out the duplicate results. The object is registered to `cvRouter` via the method `addResultFilter()`. - ```js - cvRouter.addResultFilter(filter); - ``` - -> Read more on [Capture Vision Router](https://www.dynamsoft.com/capture-vision/docs/core/architecture/#capture-vision-router). - -### Run the example - -You can run the example deployed to [the Dynamsoft Demo Server](https://demo.dynamsoft.com/Samples/DBR/JS/hello-world/hello-world.html?ver=10.5.30&utm_source=guide) or test it with [JSFiddle code editor](https://jsfiddle.net/DynamsoftTeam/csm2f9wb/). - -You will be asked to allow access to your camera, after which the video will be displayed on the page. After that, you can point the camera at a barcode to read it. - -When a barcode is decoded, you will see the result text show up under the video and the barcode location will be highlighted in the video feed. - -Alternatively, you can test locally by copying and pasting the code shown above into a local file (e.g. "hello-world.html") and opening it in your browser. - -> *Secure Contexts*: -> -> If you open the web page as `http://` , our SDK may not work correctly because the [MediaDevices: getUserMedia()](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia) and other methods only work in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS, `localhost`, `127.0.0.1`, `file://`), in some or all supporting browsers. -> -> Regarding configuring https on your server, these guides for [nginx](https://nginx.org/en/docs/http/configuring_https_servers.html) / [IIS](https://aboutssl.org/how-to-create-a-self-signed-certificate-in-iis/) / [tomcat](https://dzone.com/articles/setting-ssl-tomcat-5-minutes) / [nodejs](https://nodejs.org/docs/v0.4.1/api/tls.html) might help. -> -> If the test doesn't go as expected, you can [contact us](https://www.dynamsoft.com/company/contact/?ver=10.5.30&utm_source=guide&product=dbr&package=js). - -## Preparing the SDK - -### Step 1: Include the SDK - -
- - -
-
Use a public CDN
- -The simplest way to include the SDK is to use either the [jsDelivr](https://jsdelivr.com/) or [UNPKG](https://unpkg.com/) CDN. The "hello world" example above uses **jsDelivr**. - -- jsDelivr - - ```html - - ``` - -- UNPKG - - ```html - - ``` - - - -- In frameworks like React, Vue and Angular, you may want to add the package as a dependency. - - ```sh - npm i dynamsoft-barcode-reader-bundle@10.5.3000 -E - # or - yarn add dynamsoft-barcode-reader-bundle@10.5.3000 -E - ``` - - NOTE that in frameworks, you need to [specify the location of the engine files](#2-optional-specify-the-location-of-the-engine-files). -
- -
-
Host the SDK yourself
- -Besides using the public CDN, you can also download the SDK and host its files on your own server or a commercial CDN before including it in your application. - -- From the website - - [Download Dynamsoft Barcode Reader JavaScript Package](https://www.dynamsoft.com/barcode-reader/downloads/?ver=10.5.30&utm_source=guide&product=dbr&package=js) - - The resources are located at path `dynamsoft/distributables/@`. - -- From npm - - ```sh - npm i dynamsoft-barcode-reader-bundle@10.5.3000 -E - # Compared with using CDN, you need to set up more resources. - npm i dynamsoft-capture-vision-std@1.4.21 -E - npm i dynamsoft-image-processing@2.4.31 -E - ``` - - The resources are located at the path `node_modules/`, without `@`. You must copy "dynamsoft-xxx" packages elsewhere and add `@`. The `` can be obtained from `package.json` of each package. Another thing to do is to [specify the engineResourcePaths](#2-optional-specify-the-location-of-the-engine-files) so that the SDK can correctly locate the resources. - > Since "node_modules" is reserved for Node.js dependencies, and in our case the package is used only as static resources, we recommend either renaming the "node_modules" folder or moving the "dynamsoft-" packages to a dedicated folder for static resources in your project to facilitate self-hosting. - -You can typically include SDK like this: - -```html - -``` -
- -
- -*Note*: - -* Certain legacy web application servers may lack support for the `application/wasm` mimetype for .wasm files. To address this, you have two options: - 1. Upgrade your web application server to one that supports the `application/wasm` mimetype. - 2. Manually define the mimetype on your server. You can refer to the guides for [apache](https://developer.mozilla.org/en-US/docs/Learn/Server-side/Apache_Configuration_htaccess#media_types_and_character_encodings) / [IIS](https://docs.microsoft.com/en-us/iis/configuration/system.webserver/staticcontent/mimemap) / [nginx](https://www.nginx.com/resources/wiki/start/topics/examples/full/#mime-types). - -* To work properly, the SDK requires a few engine files, which are relatively large and may take quite a few seconds to download. We recommend that you set a longer cache time for these engine files, to maximize the performance of your web application. - - ``` - Cache-Control: max-age=31536000 - ``` - - Reference: [Cache-Control](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control). - -### Step 2: Prepare the SDK - -Before using the SDK, you need to configure a few things. - -#### 1. Specify the license - -To enable the SDK's functionality, you must provide a valid license. Utilize the API function initLicense to set your license key. - -```javascript -Dynamsoft.License.LicenseManager.initLicense("DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9"); -``` - -As previously stated, the key "DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9" serves as a test license valid for 24 hours, applicable to any newly authorized browser. To test the SDK further, you can request a 30-day free trial license via the Request a Trial License link. - -> Upon registering a Dynamsoft account and obtaining the SDK package from the official website, Dynamsoft will automatically create a 30-day free trial license and embed the corresponding license key into all the provided SDK samples. - -#### 2. [Optional] Specify the location of the "engine" files - -This step is generally necessary when utilizing frameworks such as Angular, React, Vue, or when managing the hosting of resource files yourself. - -The purpose is to tell the SDK where to find the engine files (\*.worker.js, \*.wasm.js and \*.wasm, etc.). - -```ts -// in framework -import { CoreModule } from "dynamsoft-barcode-reader-bundle"; -CoreModule.engineResourcePaths.rootDirectory = "https://cdn.jsdelivr.net/npm/"; -``` -```js -// in pure js -Dynamsoft.Core.CoreModule.engineResourcePaths.rootDirectory = "https://cdn.jsdelivr.net/npm/"; -``` -These code uses the jsDelivr CDN as an example, feel free to change it to your own location. - -## Using the SDK - -### Step 1: Preload the module - -The image processing logic is encapsulated within .wasm library files, and these files may require some time for downloading. To enhance the speed, we advise utilizing the following method to preload the libraries. - -```js -// Preload the .wasm files -await Dynamsoft.Core.CoreModule.loadWasm(["dbr"]); -``` - -### Step 2: Create a CaptureVisionRouter object - -To use the SDK, we first create a `CaptureVisionRouter` object. - -```javascript -Dynamsoft.License.LicenseManager.initLicense("DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9"); - -let cvRouter = null; -try { - cvRouter = await Dynamsoft.CVR.CaptureVisionRouter.createInstance(); -} catch (ex) { - console.error(ex); -} -``` - -*Tip*: - -When creating a `CaptureVisionRouter` object within a function which may be called more than once, it's best to use a "helper" variable to avoid double creation such as `pCvRouter` in the following code: - -```javascript -Dynamsoft.License.LicenseManager.initLicense("DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9"); - -let pCvRouter = null; // The helper variable which is a promise of cvRouter -let cvRouter = null; - -document.getElementById('btn-scan').addEventListener('click', async () => { - try { - cvRouter = await (pCvRouter = pCvRouter || Dynamsoft.CVR.CaptureVisionRouter.createInstance()); - } catch (ex) { - console.error(ex); - } -}); -``` - -### Step 3: Connect an image source - -The `CaptureVisionRouter` object, denoted as `cvRouter`, is responsible for handling images provided by an image source. In our scenario, we aim to detect barcodes directly from a live video stream. To facilitate this, we initialize a `CameraEnhancer` object, identified as `cameraEnhancer`, which is specifically designed to capture image frames from the video feed and subsequently forward them to `cvRouter`. - -To enable video streaming on the webpage, we create a `CameraView` object referred to as `cameraView`, which is then passed to `cameraEnhancer`, and its content is displayed on the webpage. - -```html -
-``` - -```javascript -let cameraView = await Dynamsoft.DCE.CameraView.createInstance(); -let cameraEnhancer = await Dynamsoft.DCE.CameraEnhancer.createInstance(cameraView); -document.querySelector("#camera-view-container").append(cameraView.getUIElement()); -cvRouter.setInput(cameraEnhancer); -``` - -### Step 4: Register a result receiver - -Once the image processing is complete, the results are sent to all the registered `CapturedResultReceiver` objects. Each `CapturedResultReceiver` object may encompass one or multiple callback functions associated with various result types. This time we use `onCapturedResultReceived`: - - -```javascript -const resultsContainer = document.querySelector("#results"); -const resultReceiver = new Dynamsoft.CVR.CapturedResultReceiver(); -resultReceiver.onCapturedResultReceived = (result) => { - if (result.barcodeResultItems?.length) { - resultsContainer.textContent = ''; - for (let item of result.barcodeResultItems) { - // In this example, the barcode results are displayed on the page below the video. - resultsContainer.textContent += `${item.formatString}: ${item.text}\n\n`; - } - } -}; -cvRouter.addResultReceiver(resultReceiver); -``` - -You can also write code like this. It is the same. - -```javascript -const resultsContainer = document.querySelector("#results"); -cvRouter.addResultReceiver({ onCapturedResultReceived: (result) => { - if (result.barcodeResultItems?.length) { - resultsContainer.textContent = ''; - for (let item of result.barcodeResultItems) { - // In this example, the barcode results are displayed on the page below the video. - resultsContainer.textContent += `${item.formatString}: ${item.text}\n\n`; - } - } -}}); -``` - -Check out [CapturedResultReceiver](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/capture-vision-router/captured-result-receiver.html) for more information. - -### Step 5: Start process video frames - -With the setup now complete, we can proceed to process the images in two straightforward steps: - -1. Initiate the image source to commence image acquisition. In our scenario, we invoke the `open()` method on `cameraEnhancer` to initiate video streaming and simultaneously initiate the collection of images. These collected images will be dispatched to `cvRouter` as per its request. -2. Define a preset template to commence image processing. In our case, we utilize the "ReadSingleBarcode" template, specifically tailored for processing images containing a single barcode. - -```javascript -await cameraEnhancer.open(); -await cvRouter.startCapturing("ReadSingleBarcode"); -``` - -*Note*: - -* `cvRouter` is engineered to consistently request images from the image source. -* Various preset templates are at your disposal for barcode reading: - -| Template Name | Function Description | -| ------------------------------ | -------------------------------------------------------------- | -| **ReadBarcodes_Default** | Scans multiple barcodes by default setting. | -| **ReadSingleBarcode** | Quickly scans a single barcode. | -| **ReadBarcodes_SpeedFirst** | Prioritizes speed in scanning multiple barcodes. | -| **ReadBarcodes_ReadRateFirst** | Maximizes the number of barcodes read. | -| **ReadBarcodes_Balance** | Balances speed and quantity in reading multiple barcodes. | -| **ReadDenseBarcodes** | Specialized in reading barcodes with high information density. | -| **ReadDistantBarcodes** | Capable of reading barcodes from extended distances. | - -Read more on the [preset CaptureVisionTemplates](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/capture-vision-router/preset-templates.html). - -## Customizing the process - -### 1. Adjust the preset template settings - -When making adjustments to some basic tasks, we often only need to modify [SimplifiedCaptureVisionSettings](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/capture-vision-router/interfaces/simplified-capture-vision-settings.html). - -#### 1.1. Change barcode settings - -The preset templates can be updated to meet different requirements. For example, the following code limits the barcode format to QR code. - -```javascript -let settings = await cvRouter.getSimplifiedSettings("ReadSingleBarcode"); -settings.barcodeSettings.barcodeFormatIds = - Dynamsoft.DBR.EnumBarcodeFormat.BF_QR_CODE; -await cvRouter.updateSettings("ReadSingleBarcode", settings); -await cvRouter.startCapturing("ReadSingleBarcode"); -``` - -For a list of adjustable barcode settings, check out [SimplifiedBarcodeReaderSettings](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/interfaces/simplified-barcode-reader-settings.html) and [EnumBarcodeFormat](https://www.dynamsoft.com/capture-vision/docs/core/enums/barcode-reader/barcode-format.html?lang=js&product=dbr). - -#### 1.2. Retrieve the original image - -Additionally, we have the option to modify the template to retrieve the original image containing the barcode. - -```javascript -let settings = await cvRouter.getSimplifiedSettings("ReadSingleBarcode"); -settings.capturedResultItemTypes |= - Dynamsoft.Core.EnumCapturedResultItemType.CRIT_ORIGINAL_IMAGE; -await cvRouter.updateSettings("ReadSingleBarcode", settings); -await cvRouter.startCapturing("ReadSingleBarcode"); -``` - -Limit the barcode format to QR code, and retrieve the original image containing the barcode, at the same time. - -```javascript -let settings = await cvRouter.getSimplifiedSettings("ReadSingleBarcode"); -settings.capturedResultItemTypes = - Dynamsoft.DBR.EnumBarcodeFormat.BF_QR_CODE | - Dynamsoft.Core.EnumCapturedResultItemType.CRIT_ORIGINAL_IMAGE; -await cvRouter.updateSettings("ReadSingleBarcode", settings); -await cvRouter.startCapturing("ReadSingleBarcode"); -``` - -Please be aware that it is necessary to update the `CapturedResultReceiver` object to obtain the original image. For instance: - -```javascript -const EnumCRIT = Dynamsoft.Core.EnumCapturedResultItemType; -resultReceiver.onCapturedResultReceived = (result) => { - if (result.barcodeResultItems?.length) { - // Use a filter to get the image on which barcodes are found. - let image = result.items.filter( - item => item.type === EnumCRIT.CRIT_ORIGINAL_IMAGE - )[0].imageData; - } -}; -``` - -#### 1.3. Change reading frequency to save power - -The SDK is initially configured to process images sequentially without any breaks. Although this setup maximizes performance, it can lead to elevated power consumption, potentially causing the device to overheat. In many cases, it's possible to reduce the reading speed while still satisfying business requirements. The following code snippet illustrates how to adjust the SDK to process an image every 500 milliseconds: - -> Please bear in mind that in the following code, if an image's processing time is shorter than 500 milliseconds, the SDK will wait for the full 500 milliseconds before proceeding to process the next image. Conversely, if an image's processing time exceeds 500 milliseconds, the subsequent image will be processed immediately upon completion. - -```javascript -let settings = await cvRouter.getSimplifiedSettings("ReadSingleBarcode"); -settings.minImageCaptureInterval = 500; -await cvRouter.updateSettings("ReadSingleBarcode", settings); -await cvRouter.startCapturing("ReadSingleBarcode"); -``` - -#### 1.4. Specify a scan region - -We can specify a scan region to allow the SDK to process only part of the image, improving processing speed. The code snippet below demonstrates how to do this using the `cameraEnhancer` image source. - -```javascript -cameraEnhancer = await Dynamsoft.DCE.CameraEnhancer.createInstance(cameraView); -// In this example, we set the scan region to cover the central 25% of the image. -cameraEnhancer.setScanRegion({ - x: 25, - y: 25, - width: 50, - height: 50, - isMeasuredInPercentage: true, -}); -``` - -*Note*: - -1. By configuring the region at the image source, images are cropped before processing, removing the need to adjust any further processing settings. -2. `cameraEnhancer` enhances interactivity by overlaying a mask on the video, clearly marking the scanning region. - -*See Also*: - -[CameraEnhancer::setScanRegion](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/acquisition.html#setscanregion) - - - - - - -### 2. Edit the preset templates directly - -The preset templates have many more settings that can be customized to suit your use case best. If you [download the SDK from Dynamsoft website](https://www.dynamsoft.com/barcode-reader/downloads/1000003-confirmation/), you can find the templates under - -* "/dynamsoft-barcode-reader-js-10.5.3000/dynamsoft/templates/" - -Upon completing the template editing, you can invoke the `initSettings` method and provide it with the template path as an argument. - -```javascript -await cvRouter.initSettings("PATH-TO-THE-FILE"); // E.g. "https://your-website/ReadSingleBarcode.json") -await cvRouter.startCapturing("ReadSingleBarcode"); // Make sure the name matches one of the CaptureVisionTemplates in the template JSON file. -``` - -### 3. [Important] Filter the results - -When processing video frames, the same barcode is often detected multiple times. To improve the user experience, we can use the [MultiFrameResultCrossFilter](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/utility/multi-frame-result-cross-filter.html) object. This object provides two methods for handling duplicate detections, which can be used independently or together, depending on what best suits your application needs: - -#### Method 1: Verify results across multiple frames - -```js -let filter = new Dynamsoft.Utility.MultiFrameResultCrossFilter(); -filter.enableResultCrossVerification("barcode", true); -await cvRouter.addResultFilter(filter); -``` - -*Note*: - -* `enableResultCrossVerification` was designed to cross-validate the outcomes across various frames in a video streaming scenario, enhancing the reliability of the final results. This validation is particularly crucial for barcodes with limited error correction capabilities, such as 1D codes. - -#### Method 2: Eliminate redundant results detected within a short time frame - -```js -let filter = new Dynamsoft.Utility.MultiFrameResultCrossFilter(); -filter.enableResultDeduplication("barcode", true); -await cvRouter.addResultFilter(filter); -``` - -*Note*: - -* `enableResultDeduplication` was designed to prevent high usage in video streaming scenarios, addressing the repetitive processing of the same code within a short period of time. - -Initially, the filter is set to forget a result 3 seconds after it is first received. During this time frame, if an identical result appears, it is ignored. - -> It's important to know that in version 9.x or earlier, the occurrence of an identical result would reset the timer, thus reinitiating the 3-second count at that point. However, in version 10.2.10 and later, an identical result no longer resets the timer but is instead disregarded, and the duration count continues uninterrupted. - -Under certain circumstances, this duration can be extended with the method `setDuplicateForgetTime()`. - -```js -let filter = new Dynamsoft.Utility.MultiFrameResultCrossFilter(); -filter.setDuplicateForgetTime(5000); // Extend the duration to 5 seconds. -await cvRouter.addResultFilter(filter); -``` - -You can also enable both options at the same time: - -```js -let filter = new Dynamsoft.Utility.MultiFrameResultCrossFilter(); -filter.enableResultCrossVerification("barcode", true); -filter.enableResultDeduplication("barcode", true); -filter.setDuplicateForgetTime(5000); -await cvRouter.addResultFilter(filter); -``` - -### 4. Add feedback - -When a barcode is detected within the video stream, its position is immediately displayed within the video. Furthermore, utilizing the "Dynamsoft Camera Enhancer" SDK, we can introduce feedback mechanisms, such as emitting a "beep" sound or triggering a "vibration". - -The following code snippet adds a "beep" sound for when a barcode is found: - -```js -const resultReceiver = new Dynamsoft.CVR.CapturedResultReceiver(); -resultReceiver.onDecodedBarcodesReceived = (result) => { - if (result.barcodeResultItems.length > 0) { - Dynamsoft.DCE.Feedback.beep(); - } -}; -cvRouter.addResultReceiver(resultReceiver); -``` - -## Customizing the UI - -```javascript -// Create a CameraView instance with default settings -let cameraView = await Dynamsoft.DCE.CameraView.createInstance(); -// Create a CameraView instance with a specified HTML file path, typically a local or remote URL -let cameraView1 = await Dynamsoft.DCE.CameraView.createInstance('@engineResourcePath/dce.mobile-native.ui.html'); -// Create a CameraView instance within a specified DOM element -let cameraView2 = await Dynamsoft.DCE.CameraView.createInstance(document.getElementById('my-ui')); -// Create a CameraView instance using a custom UI file path -let cameraView3 = await Dynamsoft.DCE.CameraView.createInstance('url/to/my/ui.html'); - -// Get the UI element associated with the cameraView instance -let uiElement = cameraView.getUIElement(); -// Remove the camera selection dropdown from the CameraView's UI element -uiElement.shadowRoot.querySelector('.dce-sel-camera').remove(); -// Remove the resolution selection dropdown from the CameraView's UI element -uiElement.shadowRoot.querySelector('.dce-sel-resolution').remove(); -``` - -The UI is part of the auxiliary SDK "Dynamsoft Camera Enhancer", read more on how to [customize the UI](https://www.dynamsoft.com/barcode-reader/docs/core/programming/features/ui-customization-js.html?lang=js). - -## Documentation - -### API Reference - -You can check out the detailed documentation about the APIs of the SDK at -[https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/?ver=10.5.3000](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/?ver=10.5.3000). - - - -### How to Upgrade - -If you want to upgrade the SDK from an old version to a newer one, please see [how to upgrade](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/upgrade-guide/index.html?ver=10.5.3000&utm_source=guide). - -### Release Notes - -Learn about what are included in each release at [https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/release-notes/index.html](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/release-notes/index.html?ver=10.5.30&utm_source=guide). - -## Next Steps - -Now that you have got the SDK integrated, you can choose to move forward in the following directions - -1. Learn how to [Use in Framework](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/user-guide/use-in-framework.html) -2. Check out the [Official Samples and Demo](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/index.html?ver=10.5.30) -3. Learn about the [APIs of the SDK](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/index.html?ver=10.5.3000) diff --git a/programming/javascript/user-guide/index-v11.0.3000.md b/programming/javascript/user-guide/index-v11.0.3000.md deleted file mode 100644 index 661ef324..00000000 --- a/programming/javascript/user-guide/index-v11.0.3000.md +++ /dev/null @@ -1,754 +0,0 @@ ---- -layout: default-layout -title: v11.0.3000 User Guide - Dynamsoft Barcode Reader JavaScript Edition -description: This is the user guide of Dynamsoft Barcode Reader JavaScript SDK. -keywords: user guide, javascript, js -breadcrumbText: User Guide -noTitleIndex: true -needGenerateH3Content: true -needAutoGenerateSidebar: true -schema: schemas/dynamsoft-facilitates-mit-research-schema.json ---- - - - -# Barcode Reader for Your Website - User Guide - -[Dynamsoft Barcode Reader JavaScript Edition](https://www.dynamsoft.com/barcode-reader/sdk-javascript/) (DBR-JS) is equipped with industry-leading algorithms for exceptional speed, accuracy and read rates in barcode reading. Using its well-designed API, you can turn your web page into a barcode scanner with just a few lines of code. Once the DBR-JS SDK gets integrated into your web page, your users can access a camera via the browser and read barcodes directly from its video input. - - - -In this guide, you will learn step by step on how to integrate the DBR-JS SDK into your website. - -Table of Contents - -- [Barcode Reader for Your Website - User Guide](#barcode-reader-for-your-website---user-guide) - - [Hello World - Simplest Implementation](#hello-world---simplest-implementation) - - [Understand the code](#understand-the-code) - - [About the code](#about-the-code) - - [Run the example](#run-the-example) - - [Preparing the SDK](#preparing-the-sdk) - - [Step 1: Include the SDK](#step-1-include-the-sdk) - - [Step 2: Prepare the SDK](#step-2-prepare-the-sdk) - - [1. Specify the license](#1-specify-the-license) - - [2. \[Optional\] Specify the location of the "engine" files](#2-optional-specify-the-location-of-the-engine-files) - - [Using the SDK](#using-the-sdk) - - [Step 1: Preload the module](#step-1-preload-the-module) - - [Step 2: Create a CaptureVisionRouter object](#step-2-create-a-capturevisionrouter-object) - - [Step 3: Connect an image source](#step-3-connect-an-image-source) - - [Step 4: Register a result receiver](#step-4-register-a-result-receiver) - - [Step 5: Start process video frames](#step-5-start-process-video-frames) - - [Customizing the process](#customizing-the-process) - - [1. Adjust the preset template settings](#1-adjust-the-preset-template-settings) - - [1.1. Change barcode settings](#11-change-barcode-settings) - - [1.2. Retrieve the original image](#12-retrieve-the-original-image) - - [1.3. Change reading frequency to save power](#13-change-reading-frequency-to-save-power) - - [1.4. Specify a scan region](#14-specify-a-scan-region) - - [2. Edit the preset templates directly](#2-edit-the-preset-templates-directly) - - [3. \[Important\] Filter the results](#3-important-filter-the-results) - - [Method 1: Verify results across multiple frames](#method-1-verify-results-across-multiple-frames) - - [Method 2: Eliminate redundant results detected within a short time frame](#method-2-eliminate-redundant-results-detected-within-a-short-time-frame) - - [4. Add feedback](#4-add-feedback) - - [Customizing the UI](#customizing-the-ui) - - [Documentation](#documentation) - - [API Reference](#api-reference) - - [How to Upgrade](#how-to-upgrade) - - [Release Notes](#release-notes) - - [Next Steps](#next-steps) - -**Popular Examples** - -- Hello World - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v11.0.30/foundational-api-samples/hello-world/hello-world.html) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/foundational-api-samples/hello-world/hello-world.html?ver=11.0.30&utm_source=guide) -- Angular App - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v11.0.30/foundational-api-samples/hello-world/angular) -- React App - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v11.0.30/foundational-api-samples/hello-world/react) -- Vue App - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v11.0.30/foundational-api-samples/hello-world/vue) -- PWA App - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v11.0.30/foundational-api-samples/hello-world/pwa) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/foundational-api-samples/hello-world/pwa/helloworld-pwa.html?ver=11.0.30&utm_source=guide) -- WebView in Android and iOS - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/v11.0.30/foundational-api-samples/hello-world/webview) -- Read Driver Licenses - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v11.0.30/foundational-api-samples/use-case/read-a-drivers-license/index.html) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/foundational-api-samples/use-case/read-a-drivers-license/index.html?ver=11.0.30&utm_source=guide) -- Fill A Form - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v11.0.30/foundational-api-samples/use-case/fill-a-form-with-barcode-reading.html) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/foundational-api-samples/use-case/fill-a-form-with-barcode-reading.html?ver=11.0.30&utm_source=guide) -- Show result information on the video - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v11.0.30/foundational-api-samples/use-case/show-result-texts-on-the-video.html) \| [Run](https://demo.dynamsoft.com/Samples/DBR/JS/foundational-api-samples/use-case/show-result-texts-on-the-video.html?ver=11.0.30&utm_source=guide) -- Debug Camera and Collect Video Frame - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/blob/v11.0.30/foundational-api-samples/others/debug) - -You can also: - -- Try the Official Demo - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-demo/) \| [Run](https://demo.dynamsoft.com/barcode-reader-js/?ver=11.0.30&utm_source=guide) -- Try Online Examples - [Github](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/v11.0.30/) - -## Hello World - Simplest Implementation - -Let's start with the "Hello World" example of the DBR-JS SDK which demonstrates how to use the minimum code to enable a web page to read barcodes from a live video stream. - -**Basic Requirements** - - - Internet connection - - A supported browser - - Camera access - -> Please refer to [system requirements](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/faq/system-requirement.html) for more details. - -### Understand the code - -The complete code of the "Hello World" example is shown below - -```html - - - -
- - - - - -``` - - - -

- - Code in Github - -   - - Run via JSFiddle - -   - - Run in Dynamsoft - -

- -> Don't want to deal with too many details? You can get a quick start with the [BarcodeScanner >>](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/user-guide/barcode-scanner.html) -> ```js -> // Scan instantly with a single line of code! -> new Dynamsoft.BarcodeScanner().launch().then(result=>alert(result.barcodeResults[0].text)); -> ``` - ------ - -#### About the code - -- `Dynamsoft.License.LicenseManager.initLicense()`: This method initializes the license for using the SDK in the application. Note that the string "**DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9**" used in this example points to an online license that requires a network connection to work. Read more on [Specify the license](#1-specify-the-license). - -- `Dynamsoft.Core.CoreModule.loadWasm()`: This is an optional code. Used to load wasm resources in advance, reducing latency between video playing and barcode decoding. - -- `Dynamsoft.CVR.CaptureVisionRouter.createInstance()`: This method creates a `CaptureVisionRouter` object `cvRouter` which controls the entire process in three steps: - - **Retrieve Images from the Image Source** - - `cvRouter` connects to the image source through the [ImageSourceAdapter](https://www.dynamsoft.com/capture-vision/docs/core/architecture/input.html#image-source-adapter?lang=js) interface with the method `setInput()`. - ```js - cvRouter.setInput(cameraEnhancer); - ``` - > The image source in our case is a [CameraEnhancer](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/user-guide/index.html) object created with `Dynamsoft.DCE.CameraEnhancer.createInstance(cameraView)` - - **Coordinate Image-Processing Tasks** - - The coordination happens behind the scenes. `cvRouter` starts the process by specifying a preset template "ReadSingleBarcode" in the method `startCapturing()`. - ```js - cvRouter.startCapturing("ReadSingleBarcode"); - ``` - - **Dispatch Results to Listening Objects** - - The processing results are returned through the [CapturedResultReceiver](https://www.dynamsoft.com/capture-vision/docs/core/architecture/output.html#captured-result-receiver?lang=js) interface. The `CapturedResultReceiver` object is registered to `cvRouter` via the method `addResultReceiver()`. For more information, please check out [Register a result receiver](#step-4-register-a-result-receiver). - ```js - cvRouter.addResultReceiver({/*The-CapturedResultReceiver-Object"*/}); - ``` - - Also note that reading from video is extremely fast and there could be many duplicate results. We can use a [filter](#3-important-filter-the-results) with result deduplication enabled to filter out the duplicate results. The object is registered to `cvRouter` via the method `addResultFilter()`. - ```js - cvRouter.addResultFilter(filter); - ``` - -> Read more on [Capture Vision Router](https://www.dynamsoft.com/capture-vision/docs/core/architecture/#capture-vision-router). - -### Run the example - -You can run the example deployed to [the Dynamsoft Demo Server](https://demo.dynamsoft.com/Samples/DBR/JS/hello-world/hello-world.html?ver=11.0.30&utm_source=guide) or test it with [JSFiddle code editor](https://jsfiddle.net/DynamsoftTeam/csm2f9wb/). - -You will be asked to allow access to your camera, after which the video will be displayed on the page. After that, you can point the camera at a barcode to read it. - -When a barcode is decoded, you will see the result text show up under the video and the barcode location will be highlighted in the video feed. - -Alternatively, you can test locally by copying and pasting the code shown above into a local file (e.g. "hello-world.html") and opening it in your browser. - -> *Secure Contexts*: -> -> If you open the web page as `http://` , our SDK may not work correctly because the [MediaDevices: getUserMedia()](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia) and other methods only work in [secure contexts](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS, `localhost`, `127.0.0.1`, `file://`), in some or all supporting browsers. -> -> Regarding configuring https on your server, these guides for [nginx](https://nginx.org/en/docs/http/configuring_https_servers.html) / [IIS](https://aboutssl.org/how-to-create-a-self-signed-certificate-in-iis/) / [tomcat](https://dzone.com/articles/setting-ssl-tomcat-5-minutes) / [nodejs](https://nodejs.org/docs/v0.4.1/api/tls.html) might help. -> -> If the test doesn't go as expected, you can [contact us](https://www.dynamsoft.com/company/contact/?ver=11.0.30&utm_source=guide&product=dbr&package=js). - -## Preparing the SDK - -### Step 1: Include the SDK - -
- - -
-
Use a public CDN
- -The simplest way to include the SDK is to use either the [jsDelivr](https://jsdelivr.com/) or [UNPKG](https://unpkg.com/) CDN. The "hello world" example above uses **jsDelivr**. - -- jsDelivr - - ```html - - ``` - -- UNPKG - - ```html - - ``` - - - -- In frameworks like React, Vue and Angular, you may want to add the package as a dependency. - - ```sh - npm i dynamsoft-barcode-reader-bundle@11.0.3000 -E - # or - yarn add dynamsoft-barcode-reader-bundle@11.0.3000 -E - ``` - - NOTE that in frameworks, you need to [specify the location of the engine files](#2-optional-specify-the-location-of-the-engine-files). -
- -
-
Host the SDK yourself
- -Besides using the public CDN, you can also download the SDK and host its files on your own server or a commercial CDN before including it in your application. - -- From the website - - [Download Dynamsoft Barcode Reader JavaScript Package](https://www.dynamsoft.com/barcode-reader/downloads/?ver=11.0.30&utm_source=guide&product=dbr&package=js) - - The resources are located at path `dynamsoft/distributables/@`. - -- From npm - - ```sh - npm i dynamsoft-barcode-reader-bundle@11.0.3000 -E - # Compared with using CDN, you need to set up more resources. - npm i dynamsoft-capture-vision-std@1.4.21 -E - npm i dynamsoft-image-processing@2.4.31 -E - ``` - - The resources are located at the path `node_modules/`, without `@`. You must copy "dynamsoft-xxx" packages elsewhere and add `@`. The `` can be obtained from `package.json` of each package. Another thing to do is to [specify the engineResourcePaths](#2-optional-specify-the-location-of-the-engine-files) so that the SDK can correctly locate the resources. - > Since "node_modules" is reserved for Node.js dependencies, and in our case the package is used only as static resources, we recommend either renaming the "node_modules" folder or moving the "dynamsoft-" packages to a dedicated folder for static resources in your project to facilitate self-hosting. - -You can typically include SDK like this: - -```html - -``` -
- -
- -*Note*: - -* Certain legacy web application servers may lack support for the `application/wasm` mimetype for .wasm files. To address this, you have two options: - 1. Upgrade your web application server to one that supports the `application/wasm` mimetype. - 2. Manually define the mimetype on your server. You can refer to the guides for [apache](https://developer.mozilla.org/en-US/docs/Learn/Server-side/Apache_Configuration_htaccess#media_types_and_character_encodings) / [IIS](https://docs.microsoft.com/en-us/iis/configuration/system.webserver/staticcontent/mimemap) / [nginx](https://www.nginx.com/resources/wiki/start/topics/examples/full/#mime-types). - -* To work properly, the SDK requires a few engine files, which are relatively large and may take quite a few seconds to download. We recommend that you set a longer cache time for these engine files, to maximize the performance of your web application. - - ``` - Cache-Control: max-age=31536000 - ``` - - Reference: [Cache-Control](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control). - -### Step 2: Prepare the SDK - -Before using the SDK, you need to configure a few things. - -#### 1. Specify the license - -To enable the SDK's functionality, you must provide a valid license. Utilize the API function initLicense to set your license key. - -```javascript -Dynamsoft.License.LicenseManager.initLicense("DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9"); -``` - -As previously stated, the key "DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9" serves as a test license valid for 24 hours, applicable to any newly authorized browser. To test the SDK further, you can request a 30-day free trial license via the Request a Trial License link. - -> Upon registering a Dynamsoft account and obtaining the SDK package from the official website, Dynamsoft will automatically create a 30-day free trial license and embed the corresponding license key into all the provided SDK samples. - -#### 2. [Optional] Specify the location of the "engine" files - -This step is generally necessary when utilizing frameworks such as Angular, React, Vue, or when managing the hosting of resource files yourself. - -The purpose is to tell the SDK where to find the engine files (\*.worker.js, \*.wasm.js and \*.wasm, etc.). - -```ts -// in framework -import { CoreModule } from "dynamsoft-barcode-reader-bundle"; -CoreModule.engineResourcePaths.rootDirectory = "https://cdn.jsdelivr.net/npm/"; -``` -```js -// in pure js -Dynamsoft.Core.CoreModule.engineResourcePaths.rootDirectory = "https://cdn.jsdelivr.net/npm/"; -``` -These code uses the jsDelivr CDN as an example, feel free to change it to your own location. - -## Using the SDK - -### Step 1: Preload the module - -The image processing logic is encapsulated within .wasm library files, and these files may require some time for downloading. To enhance the speed, we advise utilizing the following method to preload the libraries. - -```js -// Preload the .wasm files -await Dynamsoft.Core.CoreModule.loadWasm(); -``` - -### Step 2: Create a CaptureVisionRouter object - -To use the SDK, we first create a `CaptureVisionRouter` object. - -```javascript -Dynamsoft.License.LicenseManager.initLicense("DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9"); - -let cvRouter = null; -try { - cvRouter = await Dynamsoft.CVR.CaptureVisionRouter.createInstance(); -} catch (ex) { - console.error(ex); -} -``` - -*Tip*: - -When creating a `CaptureVisionRouter` object within a function which may be called more than once, it's best to use a "helper" variable to avoid double creation such as `pCvRouter` in the following code: - -```javascript -Dynamsoft.License.LicenseManager.initLicense("DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9"); - -let pCvRouter = null; // The helper variable which is a promise of cvRouter -let cvRouter = null; - -document.getElementById('btn-scan').addEventListener('click', async () => { - try { - cvRouter = await (pCvRouter = pCvRouter || Dynamsoft.CVR.CaptureVisionRouter.createInstance()); - } catch (ex) { - console.error(ex); - } -}); -``` - -### Step 3: Connect an image source - -The `CaptureVisionRouter` object, denoted as `cvRouter`, is responsible for handling images provided by an image source. In our scenario, we aim to detect barcodes directly from a live video stream. To facilitate this, we initialize a `CameraEnhancer` object, identified as `cameraEnhancer`, which is specifically designed to capture image frames from the video feed and subsequently forward them to `cvRouter`. - -To enable video streaming on the webpage, we create a `CameraView` object referred to as `cameraView`, which is then passed to `cameraEnhancer`, and its content is displayed on the webpage. - -```html -
-``` - -```javascript -let cameraView = await Dynamsoft.DCE.CameraView.createInstance(); -let cameraEnhancer = await Dynamsoft.DCE.CameraEnhancer.createInstance(cameraView); -document.querySelector("#camera-view-container").append(cameraView.getUIElement()); -cvRouter.setInput(cameraEnhancer); -``` - -### Step 4: Register a result receiver - -Once the image processing is complete, the results are sent to all the registered `CapturedResultReceiver` objects. Each `CapturedResultReceiver` object may encompass one or multiple callback functions associated with various result types. This time we use `onCapturedResultReceived`: - - -```javascript -const resultsContainer = document.querySelector("#results"); -const resultReceiver = new Dynamsoft.CVR.CapturedResultReceiver(); -resultReceiver.onCapturedResultReceived = (result) => { - if (result.barcodeResultItems?.length) { - resultsContainer.textContent = ''; - for (let item of result.barcodeResultItems) { - // In this example, the barcode results are displayed on the page below the video. - resultsContainer.textContent += `${item.formatString}: ${item.text}\n\n`; - } - } -}; -cvRouter.addResultReceiver(resultReceiver); -``` - -You can also write code like this. It is the same. - -```javascript -const resultsContainer = document.querySelector("#results"); -cvRouter.addResultReceiver({ onCapturedResultReceived: (result) => { - if (result.barcodeResultItems?.length) { - resultsContainer.textContent = ''; - for (let item of result.barcodeResultItems) { - // In this example, the barcode results are displayed on the page below the video. - resultsContainer.textContent += `${item.formatString}: ${item.text}\n\n`; - } - } -}}); -``` - -Check out [CapturedResultReceiver](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/capture-vision-router/captured-result-receiver.html) for more information. - -### Step 5: Start process video frames - -With the setup now complete, we can proceed to process the images in two straightforward steps: - -1. Initiate the image source to commence image acquisition. In our scenario, we invoke the `open()` method on `cameraEnhancer` to initiate video streaming and simultaneously initiate the collection of images. These collected images will be dispatched to `cvRouter` as per its request. -2. Define a preset template to commence image processing. In our case, we utilize the "ReadSingleBarcode" template, specifically tailored for processing images containing a single barcode. - -```javascript -await cameraEnhancer.open(); -await cvRouter.startCapturing("ReadSingleBarcode"); -``` - -*Note*: - -* `cvRouter` is engineered to consistently request images from the image source. -* Various preset templates are at your disposal for barcode reading: - -| Template Name | Function Description | -| ------------------------------ | -------------------------------------------------------------- | -| **ReadBarcodes_Default** | Scans multiple barcodes by default setting. | -| **ReadSingleBarcode** | Quickly scans a single barcode. | -| **ReadBarcodes_SpeedFirst** | Prioritizes speed in scanning multiple barcodes. | -| **ReadBarcodes_ReadRateFirst** | Maximizes the number of barcodes read. | -| **ReadBarcodes_Balance** | Balances speed and quantity in reading multiple barcodes. | -| **ReadDenseBarcodes** | Specialized in reading barcodes with high information density. | -| **ReadDistantBarcodes** | Capable of reading barcodes from extended distances. | - -Read more on the [preset CaptureVisionTemplates](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/capture-vision-router/preset-templates.html). - -## Customizing the process - -### 1. Adjust the preset template settings - -When making adjustments to some basic tasks, we often only need to modify [SimplifiedCaptureVisionSettings](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/capture-vision-router/interfaces/simplified-capture-vision-settings.html). - -#### 1.1. Change barcode settings - -The preset templates can be updated to meet different requirements. For example, the following code limits the barcode format to QR code. - -```javascript -let settings = await cvRouter.getSimplifiedSettings("ReadSingleBarcode"); -settings.barcodeSettings.barcodeFormatIds = Dynamsoft.DBR.EnumBarcodeFormat.BF_QR_CODE; -await cvRouter.updateSettings("ReadSingleBarcode", settings); -await cvRouter.startCapturing("ReadSingleBarcode"); -``` - -For a list of adjustable barcode settings, check out [SimplifiedBarcodeReaderSettings](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/interfaces/simplified-barcode-reader-settings.html) and [EnumBarcodeFormat](https://www.dynamsoft.com/capture-vision/docs/core/enums/barcode-reader/barcode-format.html?lang=js&product=dbr). - -#### 1.2. Retrieve the original image - -Additionally, we have the option to modify the template to retrieve the original image containing the barcode. - -```javascript -let settings = await cvRouter.getSimplifiedSettings("ReadSingleBarcode"); -settings.outputOriginalImage = true; -await cvRouter.updateSettings("ReadSingleBarcode", settings); -await cvRouter.startCapturing("ReadSingleBarcode"); -``` - -Limit the barcode format to QR code, and retrieve the original image containing the barcode, at the same time. - -```javascript -let settings = await cvRouter.getSimplifiedSettings("ReadSingleBarcode"); -settings.outputOriginalImage = true; -settings.barcodeSettings.barcodeFormatIds = Dynamsoft.DBR.EnumBarcodeFormat.BF_QR_CODE; -await cvRouter.updateSettings("ReadSingleBarcode", settings); -await cvRouter.startCapturing("ReadSingleBarcode"); -``` - -Please be aware that it is necessary to update the `CapturedResultReceiver` object to obtain the original image. For instance: - -```javascript -const EnumCRIT = Dynamsoft.Core.EnumCapturedResultItemType; -resultReceiver.onCapturedResultReceived = (result) => { - if (result.barcodeResultItems?.length) { - // Use a filter to get the image on which barcodes are found. - let image = result.items.filter( - item => item.type === EnumCRIT.CRIT_ORIGINAL_IMAGE - )[0].imageData; - } -}; -``` - -#### 1.3. Change reading frequency to save power - -The SDK is initially configured to process images sequentially without any breaks. Although this setup maximizes performance, it can lead to elevated power consumption, potentially causing the device to overheat. In many cases, it's possible to reduce the reading speed while still satisfying business requirements. The following code snippet illustrates how to adjust the SDK to process an image every 500 milliseconds: - -> Please bear in mind that in the following code, if an image's processing time is shorter than 500 milliseconds, the SDK will wait for the full 500 milliseconds before proceeding to process the next image. Conversely, if an image's processing time exceeds 500 milliseconds, the subsequent image will be processed immediately upon completion. - -```javascript -let settings = await cvRouter.getSimplifiedSettings("ReadSingleBarcode"); -settings.minImageCaptureInterval = 500; -await cvRouter.updateSettings("ReadSingleBarcode", settings); -await cvRouter.startCapturing("ReadSingleBarcode"); -``` - -#### 1.4. Specify a scan region - -We can specify a scan region to allow the SDK to process only part of the image, improving processing speed. The code snippet below demonstrates how to do this using the `cameraEnhancer` image source. - -```javascript -cameraEnhancer = await Dynamsoft.DCE.CameraEnhancer.createInstance(cameraView); -// In this example, we set the scan region to cover the central 25% of the image. -cameraEnhancer.setScanRegion({ - x: 25, - y: 25, - width: 50, - height: 50, - isMeasuredInPercentage: true, -}); -``` - -*Note*: - -1. By configuring the region at the image source, images are cropped before processing, removing the need to adjust any further processing settings. -2. `cameraEnhancer` enhances interactivity by overlaying a mask on the video, clearly marking the scanning region. - -*See Also*: - -[CameraEnhancer::setScanRegion](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/acquisition.html#setscanregion) - - - - - - -### 2. Edit the preset templates directly - -The preset templates have many more settings that can be customized to suit your use case best. If you [download the SDK from Dynamsoft website](https://www.dynamsoft.com/barcode-reader/downloads/1000003-confirmation/), you can find the templates under - -* "/dynamsoft-barcode-reader-js-11.0.3000/dynamsoft/templates/" - -Upon completing the template editing, you can invoke the `initSettings` method and provide it with the template path as an argument. - -```javascript -await cvRouter.initSettings("PATH-TO-THE-FILE"); // E.g. "https://your-website/ReadSingleBarcode.json") -await cvRouter.startCapturing("ReadSingleBarcode"); // Make sure the name matches one of the CaptureVisionTemplates in the template JSON file. -``` - -### 3. [Important] Filter the results - -When processing video frames, the same barcode is often detected multiple times. To improve the user experience, we can use the [MultiFrameResultCrossFilter](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/utility/multi-frame-result-cross-filter.html) object. This object provides two methods for handling duplicate detections, which can be used independently or together, depending on what best suits your application needs: - -#### Method 1: Verify results across multiple frames - -```js -let filter = new Dynamsoft.Utility.MultiFrameResultCrossFilter(); -filter.enableResultCrossVerification("barcode", true); -await cvRouter.addResultFilter(filter); -``` - -*Note*: - -* `enableResultCrossVerification` was designed to cross-validate the outcomes across various frames in a video streaming scenario, enhancing the reliability of the final results. This validation is particularly crucial for barcodes with limited error correction capabilities, such as 1D codes. - -#### Method 2: Eliminate redundant results detected within a short time frame - -```js -let filter = new Dynamsoft.Utility.MultiFrameResultCrossFilter(); -filter.enableResultDeduplication("barcode", true); -await cvRouter.addResultFilter(filter); -``` - -*Note*: - -* `enableResultDeduplication` was designed to prevent high usage in video streaming scenarios, addressing the repetitive processing of the same code within a short period of time. - -Initially, the filter is set to forget a result 3 seconds after it is first received. During this time frame, if an identical result appears, it is ignored. - -> It's important to know that in version 9.x or earlier, the occurrence of an identical result would reset the timer, thus reinitiating the 3-second count at that point. However, in version 10.2.10 and later, an identical result no longer resets the timer but is instead disregarded, and the duration count continues uninterrupted. - -Under certain circumstances, this duration can be extended with the method `setDuplicateForgetTime()`. - -```js -let filter = new Dynamsoft.Utility.MultiFrameResultCrossFilter(); -filter.setDuplicateForgetTime("barcode", 5000); // Extend the duration to 5 seconds. -await cvRouter.addResultFilter(filter); -``` - -You can also enable both options at the same time: - -```js -let filter = new Dynamsoft.Utility.MultiFrameResultCrossFilter(); -filter.enableResultCrossVerification("barcode", true); -filter.enableResultDeduplication("barcode", true); -filter.setDuplicateForgetTime("barcode", 5000); -await cvRouter.addResultFilter(filter); -``` - -### 4. Add feedback - -When a barcode is detected within the video stream, its position is immediately displayed within the video. Furthermore, utilizing the "Dynamsoft Camera Enhancer" SDK, we can introduce feedback mechanisms, such as emitting a "beep" sound or triggering a "vibration". - -The following code snippet adds a "beep" sound for when a barcode is found: - -```js -const resultReceiver = new Dynamsoft.CVR.CapturedResultReceiver(); -resultReceiver.onDecodedBarcodesReceived = (result) => { - if (result.barcodeResultItems.length > 0) { - Dynamsoft.DCE.Feedback.beep(); - } -}; -cvRouter.addResultReceiver(resultReceiver); -``` - -## Customizing the UI - -```javascript -// Create a CameraView instance with default settings -let cameraView = await Dynamsoft.DCE.CameraView.createInstance(); -// Create a CameraView instance with a specified HTML file path, typically a local or remote URL -let cameraView1 = await Dynamsoft.DCE.CameraView.createInstance('@engineResourcePath/dce.mobile-native.ui.html'); -// Create a CameraView instance within a specified DOM element -let cameraView2 = await Dynamsoft.DCE.CameraView.createInstance(document.getElementById('my-ui')); -// Create a CameraView instance using a custom UI file path -let cameraView3 = await Dynamsoft.DCE.CameraView.createInstance('url/to/my/ui.html'); - -// Get the UI element associated with the cameraView instance -let uiElement = cameraView.getUIElement(); -// Remove the camera selection dropdown from the CameraView's UI element -uiElement.shadowRoot.querySelector('.dce-sel-camera').remove(); -// Remove the resolution selection dropdown from the CameraView's UI element -uiElement.shadowRoot.querySelector('.dce-sel-resolution').remove(); -``` - -The UI is part of the auxiliary SDK "Dynamsoft Camera Enhancer", read more on how to [customize the UI](https://www.dynamsoft.com/barcode-reader/docs/core/programming/features/ui-customization-js.html?lang=js). - -## Documentation - -### API Reference - -You can check out the detailed documentation about the APIs of the SDK at -[https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/?ver=11.0.3000](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/?ver=11.0.3000). - - - -### How to Upgrade - -If you want to upgrade the SDK from an old version to a newer one, please see [how to upgrade](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/upgrade-guide/index.html?ver=11.0.3000&utm_source=guide). - -### Release Notes - -Learn about what are included in each release at [https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/release-notes/index.html](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/release-notes/index.html?ver=11.0.30&utm_source=guide). - -## Next Steps - -Now that you have got the SDK integrated, you can choose to move forward in the following directions - -1. Learn how to [Use in Framework](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/user-guide/use-in-framework.html) -2. Check out the [Official Samples and Demo](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/samples-demos/index.html?ver=11.0.30) -3. Learn about the [APIs of the SDK](https://www.dynamsoft.com/barcode-reader/docs/web/programming/javascript/api-reference/index.html?ver=11.0.3000) diff --git a/programming/javascript/user-guide/use-in-framework-v10.2.1000.md b/programming/javascript/user-guide/use-in-framework-v10.2.1000.md deleted file mode 100644 index ce9f7739..00000000 --- a/programming/javascript/user-guide/use-in-framework-v10.2.1000.md +++ /dev/null @@ -1,380 +0,0 @@ ---- -layout: default-layout -title: v10.2.10 User Guide - Use Dynamsoft Barcode Reader JavaScript Edition In Framework -description: This is the user guide to integrate Dynamsoft Barcode Reader JavaScript SDK in framework. -keywords: user guide, javascript, js, barcodes, camera, images, framework, react, angular, vue -breadcrumbText: User Guide -noTitleIndex: true -needGenerateH3Content: true -needAutoGenerateSidebar: true -schema: schemas/dynamsoft-facilitates-mit-research-schema.json ---- - -# Use in Framework - User Guide - -Integrating [Dynamsoft Barcode Reader JavaScript Edition](https://www.dynamsoft.com/barcode-reader/sdk-javascript/) (DBR-JS) into frameworks like Angular, React, and Vue is a little different compared to native usage. This guide will quickly explain the common practices of integrating DBR-JS into these frameworks. - -You can also refer to [the ready-made samples for popular frameworks](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/main/hello-world) directly without reading this guide. - -## Installation - -Assuming you have an existing project using a framework, you should have a `package.json` file in your project's root directory. - -1. Open the terminal from your project root directory. -2. Install DBR-JS SDK with the following command: - -```sh -npm install dynamsoft-barcode-reader-bundle@10.2.1000 -E -``` - -3. Confirm the installation by checking the `package.json`. You should see: - -```json -{ - ... - "dependencies": { - ... - "dynamsoft-barcode-reader-bundle": "10.2.1000" - } -} -``` - -Notice that there is no `^` before `10.2.1000`. No `^` indicates an exact version, ensuring stability and avoids automatic upgrades even without `package-lock.json`. - -While we keep the SDK's external interface relatively stable, the SDK's internal communication often change with each new version. These changes can potentially lead to compatibility issues with `engineResourcePaths` settings. To prevent any unexpected difficulties and surprises, it's essential to use the exact version of the SDK. - -## Configuration - -Next, we'll create a Configuration file for the common settings related to DBR-JS. If you use TypeScript, we can name the file `dynamsoft.config.ts`. This file is not a component, so you can place it under the `lib` directory or the root directory of `src`. - -```ts -import { CoreModule } from "dynamsoft-core"; -import { LicenseManager } from "dynamsoft-license"; -import "dynamsoft-barcode-reader"; - -// Configures the paths where the .wasm files and other necessary resources for modules are located. -CoreModule.engineResourcePaths = { - std: "https://cdn.jsdelivr.net/npm/dynamsoft-capture-vision-std@1.2.10/dist/", - dip: "https://cdn.jsdelivr.net/npm/dynamsoft-image-processing@2.2.30/dist/", - core: "https://cdn.jsdelivr.net/npm/dynamsoft-core@3.2.30/dist/", - license: "https://cdn.jsdelivr.net/npm/dynamsoft-license@3.2.21/dist/", - cvr: "https://cdn.jsdelivr.net/npm/dynamsoft-capture-vision-router@2.2.30/dist/", - dbr: "https://cdn.jsdelivr.net/npm/dynamsoft-barcode-reader@10.2.10/dist/", - dce: "https://cdn.jsdelivr.net/npm/dynamsoft-camera-enhancer@4.0.3/dist/" -}; - -/** LICENSE ALERT - README - * To use the library, you need to first specify a license key using the API "initLicense()" as shown below. - */ - -LicenseManager.initLicense("DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9"); - -/** - * You can visit https://www.dynamsoft.com/customer/license/trialLicense?utm_source=github&product=dbr&package=js to get your own trial license good for 30 days. - * Note that if you downloaded this sample from Dynamsoft while logged in, the above license key may already be your own 30-day trial license. - * For more information, see https://www.dynamsoft.com/barcode-reader/programming/javascript/user-guide/?ver=10.2.10&utm_source=github#specify-the-license or contact support@dynamsoft.com. - * LICENSE ALERT - THE END - */ - -// Optional. Preload "BarcodeReader" module for reading barcodes. It will save time on the initial decoding by skipping the module loading. -CoreModule.loadWasm(["DBR"]); -``` - -In order for these settings to take effect, `dynamsoft.config.ts` must be imported before using the barcode reader. Import this file at the entry point of your application, such as in `main.ts` or the root component. If you import `dynamsoft.config.ts` within a specific subcomponent, you can achieve lazy loading, which can save bandwidth by only loading the barcode feature when needed. - -Next, we will demonstrate how to introduce `dynamsoft.config.ts` into a specific component. Don't skip the [Component for Reading Image](#Component-for-Reading-Image) section even if you only need video barcode decoding. - -## Component for Reading Image - -A component's lifecycle includes creation and destruction, making it difficult to ensure that a component won't be rebuilt. Since the [CaptureVisionRouter](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/capture-vision-router/capture-vision-router-module.html?product=dbr&lang=javascript#capturevisionrouter-class) object is associated with a [Worker](https://developer.mozilla.org/en-US/docs/Web/API/Worker), it cannot be automatically garbage collected. Therefore, we need to manually [dispose](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/capture-vision-router/instantiate.html?product=dbr&lang=javascript#dispose) of it. - -```ts -import "../../dynamsoft.config"; -import { CaptureVisionRouter } from "dynamsoft-capture-vision-router"; - -let cvRouter; - -// create cvRouter before it's needed -// for example, after the component is mounted -async mounted(){ - cvRouter = await CaptureVisionRouter.createInstance(); -} - -// dispose cvRouter when it's no longer needed -beforeUnmount(){ - cvRouter?.dispose(); // dispose cvRouter if it exists - cvRouter = null; // reset cvRouter to null -} -``` - -In scenarios where users may click the button quickly, the component might be destroyed before `cvRouter` is fully created. To handle this situation, we'll need to implement some techniques to ensure proper resource management. - -Here's an improved version of the code to address this issue: - -```ts -let pCvRouter; // promise of cvRouter - -// create cvRouter before it's needed -// for example, after the component is mounted -async mounted(){ - cvRouter = await (pCvRouter = CaptureVisionRouter.createInstance()); -} - -// dispose cvRouter when it's no longer needed -async beforeUnmount(){ - await pCvRouter; // ensure cvrouter creation is complete - cvRouter?.dispose(); // dispose cvRouter if it exists - cvRouter = null; // reset cvRouter to null -} -``` - -### Reading Barcode from an Uploaded File - -In some cases, you might need to read barcode from an uploaded file. Here's how to handle that in your component. - -```tsx -import { EnumCapturedResultItemType } from "dynamsoft-core"; - -async function captureImage(e: Event){ - // Some frameworks will wrap the event. Refer to DBRJS samples of each frameworks for details - let file = e.target.files[0]; - e.target.value = ''; // reset input - - let result = await cvRouter.capture(file, "ReadBarcodes_SpeedFirst"); - for (let item of result.items) { - // check if captured result item is a barcode - if(item.type !== EnumCapturedResultItemType.CRIT_BARCODE) { - continue; // Skip processing if the result is not a barcode - } - console.log(item.text); // output the decoded barcode text - } -} - -// usage example in a tsx/jsx component - -``` - -### Lazy Loading `cvRouter` - -To optimize resource usage, you might want to lazy load `cvRouter` only after the client uploads a file. - -```ts -async captureImage(e: Event){ - // ... - cvRouter = await (pCvRouter = CaptureVisionRouter.createInstance()); - // ... -} -``` - -Additionally, users may repeatedly upload files which can result in multiple instances being created, potentially causing memory leaks. Here's how we could handle this. - -```ts -async captureImage(e: Event){ - // ... - cvRouter = await (pCvRouter = pCvRouter || CaptureVisionRouter.createInstance()); - // ... -} -``` - -### Handling Component Destruction During Decoding - -When decoding barcodes, it's common for users to switch to another component. If you're familiar with handling network requests, you know that this situation is very common. - -Here's how we could handle with proper checks to avoid program errors: - -```ts -let isDestroyed = false; - -async captureImage(e: Event){ - // ensure cvRouter is created only once - cvRouter = await (pCvRouter = pCvRouter || CaptureVisionRouter.createInstance()); - if(isDestroyed){ return; } - // ... - let result = await cvRouter.capture(file, "ReadBarcodes_SpeedFirst"); - if(isDestroyed){ return; } - -} - -// dispose cvRouter when it's no longer needed -async beforeUnmount(){ - isDestroyed = true; - await pCvRouter; - cvRouter?.dispose(); - cvRouter = null; -} -``` - -By adding a check for `isDestroyed` after each `await`, we can ensure that the code handles the component's potential destruction properly, avoiding errors and resource leaks. - -### Complete Code Example - -```tsx -import "../../dynamsoft.config"; -import { CaptureVisionRouter } from "dynamsoft-capture-vision-router"; - -let cvRouter; -let pCvRouter; // promise of cvRouter -let isDestroyed = false; - -async captureImage(e: Event){ - // Some frameworks will wrap the event. Refer to DBRJS samples of each frameworks for details - let file = e.target.files[0]; - e.target.value = ''; // reset input - - // ensure cvRouter is created only once - cvRouter = await (pCvRouter = pCvRouter || CaptureVisionRouter.createInstance()); - if(isDestroyed){ return; } - - let result = await cvRouter.capture(file, "ReadBarcodes_SpeedFirst"); - if(isDestroyed){ return; } - - for (let item of result.items) { - // check if captured result item is a barcode - if(item.type !== EnumCapturedResultItemType.CRIT_BARCODE) { - continue; // Skip processing if the result is not a barcode - } - console.log(item.text); // output the decoded barcode text - } -} - -// dispose cvRouter when it's no longer needed -async beforeUnmount(){ - isDestroyed = true; - await pCvRouter; // ensure cvrouter creation is complete - cvRouter?.dispose(); // dispose cvRouter if it exists - cvRouter = null; // reset cvRouter to null -} - -// usage example in a tsx/jsx component - -``` - -> If you find it difficult to think about these, don't worry, just go to [DBRJS samples for framework](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/main/hello-world), copy these components into your project. - -## Component for Decoding Video - -### Set up the video ([CameraView](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/cameraview.html)) container -To render video within a component and handle its lifecycle properly, we can use framework's methods (such as `#` or `ref` or `bind:this`) to get the component's `HTMLDivElement`. This is where the video will be rendered. - -```tsx -let cameraviewContainer; - -
-``` - -### Render the Video UI - -The [`CameraEnhancer`](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/index.html) instance needs to be properly created and [disposed](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/instantiate.html#dispose) of to manage resources. - -```ts -import "../dynamsoft.config"; -import { CameraEnhancer, CameraView } from "dynamsoft-camera-enhancer"; - -let cameraEnhancer; -let pCameraEnhancer; // promise of cameraEnhancer -let isDestroyed = false; - -async mount(){ - // create a `CameraEnhancer` instance for camera control and a `CameraView` instance for UI control. - const cameraView = await CameraView.createInstance(); - if(isDestroyed){ return; } // Check if component is destroyed after every async - - cameraEnhancer = await (pCameraEnhancer || CameraEnhancer.createInstance(cameraView)); - if(isDestroyed){ return; } - - // Get default UI and append it to DOM. - cameraViewContainer.append(cameraView.getUIElement()); -} - -async beforeUnmount(){ - isDestroyed = true; - await pCameraEnhancer; - cameraEnhancer?.dispose(); - cameraEnhancer = null; -} - -// usage example in a tsx/jsx component -
-``` - -### Add [`CaptureVisionRouter`](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/capture-vision-router/capture-vision-router-module.html) - -To complete the code, we'll include the [`CaptureVisionRouter`](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/capture-vision-router/capture-vision-router-module.html) and handle it's life cycle similarly. - -```ts -import "../dynamsoft.config"; -import { CameraEnhancer, CameraView } from "dynamsoft-camera-enhancer"; -import { CaptureVisionRouter } from "dynamsoft-capture-vision-router"; - -let cameraEnhancer; -let pCameraEnhancer; // promise of cameraEnhancer -let cvRouter; -let pCvRouter; // promise of cvRouter -let isDestroyed = false; - -async mount(){ - // Create a `CameraEnhancer` instance for camera control and a `CameraView` instance for UI control. - const cameraView = await CameraView.createInstance(); - if(isDestroyed){ return; } // Check if component is destroyed after every async - - cameraEnhancer = await (pCameraEnhancer || CameraEnhancer.createInstance(cameraView)); - if(isDestroyed){ return; } - - // Get default UI and append it to DOM. - cameraViewContainer.append(cameraView.getUIElement()); - - // Create a `CaptureVisionRouter` instance and set `CameraEnhancer` instance as its image source. - cvRouter = await (pCvRouter || CaptureVisionRouter.createInstance()); - if(isDestroyed){ return; } - - cvRouter.setInput(cameraEnhancer); - - // Define a callback for results. - cvRouter.addResultReceiver({ onDecodedBarcodesReceived: (result) => { - if (!result.barcodeResultItems.length) return; - for (let item of result.barcodeResultItems) { - console.log(item.text); // output the decoded barcode text - } - }}); - - // Filter out unchecked and duplicate results. - const filter = new MultiFrameResultCrossFilter(); - // Filter out unchecked barcodes. - filter.enableResultCrossVerification("barcode", true); - // Filter out duplicate barcodes within 3 seconds. - filter.enableResultDeduplication("barcode", true); - await cvRouter.addResultFilter(filter); - if(isDestroyed){ return; } - - // Open camera and start scanning single barcode. - await cameraEnhancer.open(); - if(isDestroyed){ return; } - - await cvRouter.startCapturing("ReadSingleBarcode"); -} - -async beforeUnmount(){ - isDestroyed = true; - - await pCvRouter; - cvRouter?.dispose(); - cvRouter = null; - - await pCameraEnhancer; - cameraEnhancer?.dispose(); - cameraEnhancer = null; -} - -// usage example in a tsx/jsx component -
-``` - -### Final Notes - -Decoding video is slightly more complex than reading image, but by following the steps above, you can manage resources effectively and ensure your component runs smoothly. - -Again, if you don't want to go into detail, please refer to the [DBRJS sample](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/main/hello-world) directly. - -Note that since we have taken over native rendering, avoid changing the UI through the framework within decoding video component; instead, make changes in its parent component. - -Once this component is rendered, decoding will start. You can control when decoding occurs by not rendering this component until needed. diff --git a/programming/javascript/user-guide/use-in-framework-v10.4.2002.md b/programming/javascript/user-guide/use-in-framework-v10.4.2002.md deleted file mode 100644 index da4f0b2f..00000000 --- a/programming/javascript/user-guide/use-in-framework-v10.4.2002.md +++ /dev/null @@ -1,373 +0,0 @@ ---- -layout: default-layout -title: v10.4.20 User Guide - Use Dynamsoft Barcode Reader JavaScript Edition In Framework -description: This is the user guide to integrate Dynamsoft Barcode Reader JavaScript SDK in framework. -keywords: user guide, javascript, js, barcodes, camera, images, framework, react, angular, vue -breadcrumbText: User Guide -noTitleIndex: true -needGenerateH3Content: true -needAutoGenerateSidebar: true -schema: schemas/dynamsoft-facilitates-mit-research-schema.json ---- - -# Use in Framework - User Guide - -Integrating [Dynamsoft Barcode Reader JavaScript Edition](https://www.dynamsoft.com/barcode-reader/sdk-javascript/) (DBR-JS) into frameworks like Angular, React, and Vue is a little different compared to native usage. This guide will quickly explain the common practices of integrating DBR-JS into these frameworks. - -You can also refer to [the ready-made samples for popular frameworks](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/main/hello-world) directly without reading this guide. - -## Installation - -Assuming you have an existing project using a framework, you should have a `package.json` file in your project's root directory. - -1. Open the terminal from your project root directory. -2. Install DBR-JS SDK with the following command: - - ```sh - npm install dynamsoft-barcode-reader-bundle@10.4.2002 -E - ``` - -3. Confirm the installation by checking the `package.json`. You should see: - - ```json - { - ... - "dependencies": { - ... - "dynamsoft-barcode-reader-bundle": "10.4.2002" - } - } - ``` - -Notice that there is no `^` before `10.4.2002`. No `^` indicates an exact version, ensuring stability and avoids automatic upgrades even without `package-lock.json`. - -While we keep the SDK's external interface relatively stable, the SDK's internal communication often change with each new version. These changes can potentially lead to compatibility issues with `engineResourcePaths` settings. To prevent any unexpected difficulties and surprises, it's essential to use the exact version of the SDK. - -## Configuration - -Next, we'll create a Configuration file for the common settings related to DBR-JS. If you use TypeScript, we can name the file `dynamsoft.config.ts`. This file is not a component, so you can place it under the `lib` directory or the root directory of `src`. - -```ts -import { CoreModule } from "dynamsoft-core"; -import { LicenseManager } from "dynamsoft-license"; -import "dynamsoft-barcode-reader"; - -// Configures the root path where the .wasm files and other necessary resources for modules are located. -CoreModule.engineResourcePaths.rootDirectory = "https://cdn.jsdelivr.net/npm/"; - -/** LICENSE ALERT - README - * To use the library, you need to first specify a license key using the API "initLicense()" as shown below. - */ - -LicenseManager.initLicense("DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9"); - -/** - * You can visit https://www.dynamsoft.com/customer/license/trialLicense?utm_source=github&product=dbr&package=js to get your own trial license good for 30 days. - * Note that if you downloaded this sample from Dynamsoft while logged in, the above license key may already be your own 30-day trial license. - * For more information, see https://www.dynamsoft.com/barcode-reader/programming/javascript/user-guide/?ver=10.4.20&utm_source=github#specify-the-license or contact support@dynamsoft.com. - * LICENSE ALERT - THE END - */ - -// Optional. Preload "BarcodeReader" module for reading barcodes. It will save time on the initial decoding by skipping the module loading. -CoreModule.loadWasm(["DBR"]); -``` - -In order for these settings to take effect, `dynamsoft.config.ts` must be imported before using the barcode reader. One approach is to import this file at the entry point of the application, such as in `main.ts` or the root component. If you import `dynamsoft.config.ts` within a specific subcomponent, you can achieve lazy loading, which can save bandwidth by only loading the barcode feature when needed. - -Next, we will demonstrate how to introduce `dynamsoft.config.ts` into a specific component. Don't skip the [Component for Reading Image](#component-for-reading-image) section even if you only need video barcode decoding. - -## Component for Reading Image - -A component's lifecycle includes creation and destruction, making it difficult to ensure that a component won't be rebuilt. Since the [CaptureVisionRouter](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/capture-vision-router/capture-vision-router-module.html?product=dbr&lang=javascript#capturevisionrouter-class) object is associated with a [Worker](https://developer.mozilla.org/en-US/docs/Web/API/Worker), it cannot be automatically garbage collected. Therefore, we need to manually [dispose](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/capture-vision-router/instantiate.html?product=dbr&lang=javascript#dispose) of it. - -```ts -import "../../dynamsoft.config"; -import { CaptureVisionRouter } from "dynamsoft-capture-vision-router"; - -let cvRouter; - -// create cvRouter before it's needed -// for example, after the component is mounted -async mounted(){ - cvRouter = await CaptureVisionRouter.createInstance(); -} - -// dispose cvRouter when it's no longer needed -beforeUnmount(){ - cvRouter?.dispose(); // dispose cvRouter if it exists - cvRouter = null; // reset cvRouter to null -} -``` - -In scenarios where users may click the button quickly, the component might be destroyed before `cvRouter` is fully created. To handle this situation, we'll need to implement some techniques to ensure proper resource management. - -Here's an improved version of the code to address this issue: - -```ts -let pCvRouter; // promise of cvRouter - -// create cvRouter before it's needed -// for example, after the component is mounted -async mounted(){ - cvRouter = await (pCvRouter = CaptureVisionRouter.createInstance()); -} - -// dispose cvRouter when it's no longer needed -async beforeUnmount(){ - await pCvRouter; // ensure cvrouter creation is complete - cvRouter?.dispose(); // dispose cvRouter if it exists - cvRouter = null; // reset cvRouter to null -} -``` - -### Reading Barcode from an Uploaded File - -In some cases, you might need to read barcode from an uploaded file. Here's how to handle that in your component. - -```tsx -import { EnumCapturedResultItemType } from "dynamsoft-core"; - -async function captureImage(e: Event){ - // Some frameworks will wrap the event. Refer to DBRJS samples of each frameworks for details - let file = e.target.files[0]; - e.target.value = ''; // reset input - - let result = await cvRouter.capture(file, "ReadBarcodes_SpeedFirst"); - for (let item of result.items) { - // check if captured result item is a barcode - if(item.type !== EnumCapturedResultItemType.CRIT_BARCODE) { - continue; // Skip processing if the result is not a barcode - } - console.log(item.text); // output the decoded barcode text - } -} - -// usage example in a tsx/jsx component - -``` - -### Lazy Loading `cvRouter` - -To optimize resource usage, you might want to lazy load `cvRouter` only after the client uploads a file. - -```ts -async captureImage(e: Event){ - // ... - cvRouter = await (pCvRouter = CaptureVisionRouter.createInstance()); - // ... -} -``` - -Additionally, users may repeatedly upload files which can result in multiple instances being created, potentially causing memory leaks. Here's how we could handle this. - -```ts -async captureImage(e: Event){ - // ... - cvRouter = await (pCvRouter = pCvRouter || CaptureVisionRouter.createInstance()); - // ... -} -``` - -### Handling Component Destruction During Decoding - -When decoding barcodes, it's common for users to switch to another component. If you're familiar with handling network requests, you know that this situation is very common. - -Here's how we could handle with proper checks to avoid program errors: - -```ts -let isDestroyed = false; - -async captureImage(e: Event){ - // ensure cvRouter is created only once - cvRouter = await (pCvRouter = pCvRouter || CaptureVisionRouter.createInstance()); - if(isDestroyed){ return; } - // ... - let result = await cvRouter.capture(file, "ReadBarcodes_SpeedFirst"); - if(isDestroyed){ return; } - -} - -// dispose cvRouter when it's no longer needed -async beforeUnmount(){ - isDestroyed = true; - await pCvRouter; - cvRouter?.dispose(); - cvRouter = null; -} -``` - -By adding a check for `isDestroyed` after each `await`, we can ensure that the code handles the component's potential destruction properly, avoiding errors and resource leaks. - -### Complete Code Example - -```tsx -import "../../dynamsoft.config"; -import { CaptureVisionRouter } from "dynamsoft-capture-vision-router"; - -let cvRouter; -let pCvRouter; // promise of cvRouter -let isDestroyed = false; - -async captureImage(e: Event){ - // Some frameworks will wrap the event. Refer to DBRJS samples of each frameworks for details - let file = e.target.files[0]; - e.target.value = ''; // reset input - - // ensure cvRouter is created only once - cvRouter = await (pCvRouter = pCvRouter || CaptureVisionRouter.createInstance()); - if(isDestroyed){ return; } - - let result = await cvRouter.capture(file, "ReadBarcodes_SpeedFirst"); - if(isDestroyed){ return; } - - for (let item of result.items) { - // check if captured result item is a barcode - if(item.type !== EnumCapturedResultItemType.CRIT_BARCODE) { - continue; // Skip processing if the result is not a barcode - } - console.log(item.text); // output the decoded barcode text - } -} - -// dispose cvRouter when it's no longer needed -async beforeUnmount(){ - isDestroyed = true; - await pCvRouter; // ensure cvrouter creation is complete - cvRouter?.dispose(); // dispose cvRouter if it exists - cvRouter = null; // reset cvRouter to null -} - -// usage example in a tsx/jsx component - -``` - -> If you find it difficult to think about these, don't worry, just go to [DBRJS samples for framework](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/main/hello-world), copy these components into your project. - -## Component for Decoding Video - -### Set up the video ([CameraView](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/cameraview.html)) container - -To render video within a component and handle its lifecycle properly, we can use framework's methods (such as `#` or `ref` or `bind:this`) to get the component's `HTMLDivElement`. This is where the video will be rendered. - -```tsx -let cameraviewContainer; - -
-``` - -### Render the Video UI - -The [`CameraEnhancer`](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/index.html) instance needs to be properly created and [disposed](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/instantiate.html#dispose) of to manage resources. - -```ts -import "../dynamsoft.config"; -import { CameraEnhancer, CameraView } from "dynamsoft-camera-enhancer"; - -let cameraEnhancer; -let pCameraEnhancer; // promise of cameraEnhancer -let isDestroyed = false; - -async mount(){ - // create a `CameraEnhancer` instance for camera control and a `CameraView` instance for UI control. - const cameraView = await CameraView.createInstance(); - if(isDestroyed){ return; } // Check if component is destroyed after every async - - cameraEnhancer = await (pCameraEnhancer || CameraEnhancer.createInstance(cameraView)); - if(isDestroyed){ return; } - - // Get default UI and append it to DOM. - cameraViewContainer.append(cameraView.getUIElement()); -} - -async beforeUnmount(){ - isDestroyed = true; - await pCameraEnhancer; - cameraEnhancer?.dispose(); - cameraEnhancer = null; -} - -// usage example in a tsx/jsx component -
-``` - -### Add [`CaptureVisionRouter`](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/capture-vision-router/capture-vision-router-module.html) - -To complete the code, we'll include the [`CaptureVisionRouter`](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/capture-vision-router/capture-vision-router-module.html) and handle it's life cycle similarly. - -```ts -import "../dynamsoft.config"; -import { CameraEnhancer, CameraView } from "dynamsoft-camera-enhancer"; -import { CaptureVisionRouter } from "dynamsoft-capture-vision-router"; - -let cameraEnhancer; -let pCameraEnhancer; // promise of cameraEnhancer -let cvRouter; -let pCvRouter; // promise of cvRouter -let isDestroyed = false; - -async mount(){ - // Create a `CameraEnhancer` instance for camera control and a `CameraView` instance for UI control. - const cameraView = await CameraView.createInstance(); - if(isDestroyed){ return; } // Check if component is destroyed after every async - - cameraEnhancer = await (pCameraEnhancer || CameraEnhancer.createInstance(cameraView)); - if(isDestroyed){ return; } - - // Get default UI and append it to DOM. - cameraViewContainer.append(cameraView.getUIElement()); - - // Create a `CaptureVisionRouter` instance and set `CameraEnhancer` instance as its image source. - cvRouter = await (pCvRouter || CaptureVisionRouter.createInstance()); - if(isDestroyed){ return; } - - cvRouter.setInput(cameraEnhancer); - - // Define a callback for results. - cvRouter.addResultReceiver({ onDecodedBarcodesReceived: (result) => { - if (!result.barcodeResultItems.length) return; - for (let item of result.barcodeResultItems) { - console.log(item.text); // output the decoded barcode text - } - }}); - - // Filter out unchecked and duplicate results. - const filter = new MultiFrameResultCrossFilter(); - // Filter out unchecked barcodes. - filter.enableResultCrossVerification("barcode", true); - // Filter out duplicate barcodes within 3 seconds. - filter.enableResultDeduplication("barcode", true); - await cvRouter.addResultFilter(filter); - if(isDestroyed){ return; } - - // Open camera and start scanning single barcode. - await cameraEnhancer.open(); - if(isDestroyed){ return; } - - await cvRouter.startCapturing("ReadSingleBarcode"); -} - -async beforeUnmount(){ - isDestroyed = true; - - await pCvRouter; - cvRouter?.dispose(); - cvRouter = null; - - await pCameraEnhancer; - cameraEnhancer?.dispose(); - cameraEnhancer = null; -} - -// usage example in a tsx/jsx component -
-``` - -### Final Notes - -Decoding video is slightly more complex than reading image, but by following the steps above, you can manage resources effectively and ensure your component runs smoothly. - -Again, if you don't want to go into detail, please refer to the [DBRJS sample](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/main/hello-world) directly. - -Note that since we have taken over native rendering, avoid changing the UI through the framework within decoding video component; instead, make changes in its parent component. - -Once this component is rendered, decoding will start. You can control when decoding occurs by not rendering this component until needed. diff --git a/programming/javascript/user-guide/use-in-framework-v10.5.3000.md b/programming/javascript/user-guide/use-in-framework-v10.5.3000.md deleted file mode 100644 index aea1ae99..00000000 --- a/programming/javascript/user-guide/use-in-framework-v10.5.3000.md +++ /dev/null @@ -1,391 +0,0 @@ ---- -layout: default-layout -title: v10.5.3000 User Guide - Use Dynamsoft Barcode Reader JavaScript Edition In Framework -description: This is the user guide to integrate Dynamsoft Barcode Reader JavaScript SDK in framework. -keywords: user guide, javascript, js, barcodes, camera, images, framework, react, angular, vue -breadcrumbText: User Guide -noTitleIndex: true -needGenerateH3Content: true -needAutoGenerateSidebar: true -schema: schemas/dynamsoft-facilitates-mit-research-schema.json ---- - -# Use in Framework - User Guide - -Integrating [Dynamsoft Barcode Reader JavaScript Edition](https://www.dynamsoft.com/barcode-reader/sdk-javascript/) (DBR-JS) into frameworks like Angular, React, and Vue is a little different compared to native usage. This guide will quickly explain the common practices of integrating DBR-JS into these frameworks. - -You can also refer to [the ready-made samples for popular frameworks](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/main/foundational-api-samples/hello-world) directly without reading this guide. - -## Installation - -Assuming you have an existing project using a framework, you should have a `package.json` file in your project's root directory. - -1. Open the terminal from your project root directory. -2. Install DBR-JS SDK with the following command: - - ```sh - npm install dynamsoft-barcode-reader-bundle@10.5.3000 -E - ``` - -3. Confirm the installation by checking the `package.json`. You should see: - - ```json - { - ... - "dependencies": { - ... - "dynamsoft-barcode-reader-bundle": "10.5.3000" - } - } - ``` - -Notice that there is no `^` before `10.5.3000`. No `^` indicates an exact version, ensuring stability and avoids automatic upgrades even without `package-lock.json`. - -While we keep the SDK's external interface relatively stable, the SDK's internal communication often change with each new version. These changes can potentially lead to compatibility issues with `engineResourcePaths` settings. To prevent any unexpected difficulties and surprises, it's essential to use the exact version of the SDK. - -## Configuration - -Next, we'll create a Configuration file for the common settings related to DBR-JS. If you use TypeScript, we can name the file `dynamsoft.config.ts`. This file is not a component, so you can place it under the `lib` directory or the root directory of `src`. - -```ts -import { CoreModule } from "dynamsoft-core"; -import { LicenseManager } from "dynamsoft-license"; -import "dynamsoft-barcode-reader"; - -// Configures the root path where the .wasm files and other necessary resources for modules are located. -CoreModule.engineResourcePaths.rootDirectory = "https://cdn.jsdelivr.net/npm/"; - -/** LICENSE ALERT - README - * To use the library, you need to first specify a license key using the API "initLicense()" as shown below. - */ - -LicenseManager.initLicense("DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9"); - -/** - * You can visit https://www.dynamsoft.com/customer/license/trialLicense?utm_source=github&product=dbr&package=js to get your own trial license good for 30 days. - * Note that if you downloaded this sample from Dynamsoft while logged in, the above license key may already be your own 30-day trial license. - * For more information, see https://www.dynamsoft.com/barcode-reader/programming/javascript/user-guide/?ver=10.5.30&utm_source=github#specify-the-license or contact support@dynamsoft.com. - * LICENSE ALERT - THE END - */ - -// Optional. Preload "BarcodeReader" module for reading barcodes. It will save time on the initial decoding by skipping the module loading. -CoreModule.loadWasm(["DBR"]); -``` - -In order for these settings to take effect, `dynamsoft.config.ts` must be imported before using the barcode reader. One approach is to import this file at the entry point of the application, such as in `main.ts` or the root component. If you import `dynamsoft.config.ts` within a specific subcomponent, you can achieve lazy loading, which can save bandwidth by only loading the barcode feature when needed. - -### Offline usage - -In some cases, you may need to use DBR-JS in an offline environment. You can download the [DBR-JS zip](https://www.dynamsoft.com/barcode-reader/downloads/1000003-confirmation/#js) package through the link, which contains all the necessary offline resources in the `./distributables` directory. - -**Step 1:** Copy the `./distributables` folder to your project. - -**Step 2:** In `dynamsoft.config.ts`, define the `engineResourcePaths`: - -```javascript -// Configures the root path where the .wasm files and other necessary resources for modules are located. Feel free to change it to your own location of these files -CoreModule.engineResourcePaths.rootDirectory = '../assets/distributables'; -``` - -> Note: -> -> We recommend not renaming any module files within the `./distributables` directory, as this may cause the rootDirectory configuration to not work properly. In such cases, you would need to define resource paths for each module individually. -> In our case the packages are used only as static resources, we recommend moving the `./distributables` to a dedicated folder for static resources in your project to facilitate self-hosting. - -Next, we will demonstrate how to introduce `dynamsoft.config.ts` into a specific component. Don't skip the [Component for Reading Image](#component-for-reading-image) section even if you only need video barcode decoding. - -## Component for Reading Image - -A component's lifecycle includes creation and destruction, making it difficult to ensure that a component won't be rebuilt. Since the [CaptureVisionRouter](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/capture-vision-router/capture-vision-router-module.html?product=dbr&lang=javascript#capturevisionrouter-class) object is associated with a [Worker](https://developer.mozilla.org/en-US/docs/Web/API/Worker), it cannot be automatically garbage collected. Therefore, we need to manually [dispose](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/capture-vision-router/instantiate.html?product=dbr&lang=javascript#dispose) of it. - -```ts -import "../../dynamsoft.config"; -import { CaptureVisionRouter } from "dynamsoft-capture-vision-router"; - -let cvRouter; - -// create cvRouter before it's needed -// for example, after the component is mounted -async mounted(){ - cvRouter = await CaptureVisionRouter.createInstance(); -} - -// dispose cvRouter when it's no longer needed -beforeUnmount(){ - cvRouter?.dispose(); // dispose cvRouter if it exists - cvRouter = null; // reset cvRouter to null -} -``` - -In scenarios where users may click the button quickly, the component might be destroyed before `cvRouter` is fully created. To handle this situation, we'll need to implement some techniques to ensure proper resource management. - -Here's an improved version of the code to address this issue: - -```ts -let pCvRouter; // promise of cvRouter - -// create cvRouter before it's needed -// for example, after the component is mounted -async mounted(){ - cvRouter = await (pCvRouter = CaptureVisionRouter.createInstance()); -} - -// dispose cvRouter when it's no longer needed -async beforeUnmount(){ - await pCvRouter; // ensure cvrouter creation is complete - cvRouter?.dispose(); // dispose cvRouter if it exists - cvRouter = null; // reset cvRouter to null -} -``` - -### Reading Barcode from an Uploaded File - -In some cases, you might need to read barcode from an uploaded file. Here's how to handle that in your component. - -```tsx -import { EnumCapturedResultItemType } from "dynamsoft-core"; - -async function captureImage(e: Event){ - // Some frameworks will wrap the event. Refer to DBRJS samples of each frameworks for details - let file = e.target.files[0]; - e.target.value = ''; // reset input - - let result = await cvRouter.capture(file, "ReadBarcodes_SpeedFirst"); - for (let item of result.items) { - // check if captured result item is a barcode - if(item.type !== EnumCapturedResultItemType.CRIT_BARCODE) { - continue; // Skip processing if the result is not a barcode - } - console.log(item.text); // output the decoded barcode text - } -} - -// usage example in a tsx/jsx component - -``` - -### Lazy Loading `cvRouter` - -To optimize resource usage, you might want to lazy load `cvRouter` only after the client uploads a file. - -```ts -async captureImage(e: Event){ - // ... - cvRouter = await (pCvRouter = CaptureVisionRouter.createInstance()); - // ... -} -``` - -Additionally, users may repeatedly upload files which can result in multiple instances being created, potentially causing memory leaks. Here's how we could handle this. - -```ts -async captureImage(e: Event){ - // ... - cvRouter = await (pCvRouter = pCvRouter || CaptureVisionRouter.createInstance()); - // ... -} -``` - -### Handling Component Destruction During Decoding - -When decoding barcodes, it's common for users to switch to another component. If you're familiar with handling network requests, you know that this situation is very common. - -Here's how we could handle with proper checks to avoid program errors: - -```ts -let isDestroyed = false; - -async captureImage(e: Event){ - // ensure cvRouter is created only once - cvRouter = await (pCvRouter = pCvRouter || CaptureVisionRouter.createInstance()); - if(isDestroyed){ return; } - // ... - let result = await cvRouter.capture(file, "ReadBarcodes_SpeedFirst"); - if(isDestroyed){ return; } - -} - -// dispose cvRouter when it's no longer needed -async beforeUnmount(){ - isDestroyed = true; - await pCvRouter; - cvRouter?.dispose(); - cvRouter = null; -} -``` - -By adding a check for `isDestroyed` after each `await`, we can ensure that the code handles the component's potential destruction properly, avoiding errors and resource leaks. - -### Complete Code Example - -```tsx -import "../../dynamsoft.config"; -import { CaptureVisionRouter } from "dynamsoft-capture-vision-router"; - -let cvRouter; -let pCvRouter; // promise of cvRouter -let isDestroyed = false; - -async captureImage(e: Event){ - // Some frameworks will wrap the event. Refer to DBRJS samples of each frameworks for details - let file = e.target.files[0]; - e.target.value = ''; // reset input - - // ensure cvRouter is created only once - cvRouter = await (pCvRouter = pCvRouter || CaptureVisionRouter.createInstance()); - if(isDestroyed){ return; } - - let result = await cvRouter.capture(file, "ReadBarcodes_SpeedFirst"); - if(isDestroyed){ return; } - - for (let item of result.items) { - // check if captured result item is a barcode - if(item.type !== EnumCapturedResultItemType.CRIT_BARCODE) { - continue; // Skip processing if the result is not a barcode - } - console.log(item.text); // output the decoded barcode text - } -} - -// dispose cvRouter when it's no longer needed -async beforeUnmount(){ - isDestroyed = true; - await pCvRouter; // ensure cvrouter creation is complete - cvRouter?.dispose(); // dispose cvRouter if it exists - cvRouter = null; // reset cvRouter to null -} - -// usage example in a tsx/jsx component - -``` - -> If you find it difficult to think about these, don't worry, just go to [DBRJS samples for framework](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/main/hello-world), copy these components into your project. - -## Component for Decoding Video - -### Set up the video ([CameraView](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/cameraview.html)) container - -To render video within a component and handle its lifecycle properly, we can use framework's methods (such as `#` or `ref` or `bind:this`) to get the component's `HTMLDivElement`. This is where the video will be rendered. - -```tsx -let cameraviewContainer; - -
-``` - -### Render the Video UI - -The [`CameraEnhancer`](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/index.html) instance needs to be properly created and [disposed](https://www.dynamsoft.com/camera-enhancer/docs/web/programming/javascript/api-reference/instantiate.html#dispose) of to manage resources. - -```ts -import "../dynamsoft.config"; -import { CameraEnhancer, CameraView } from "dynamsoft-camera-enhancer"; - -let cameraEnhancer; -let pCameraEnhancer; // promise of cameraEnhancer -let isDestroyed = false; - -async mount(){ - // create a `CameraEnhancer` instance for camera control and a `CameraView` instance for UI control. - const cameraView = await CameraView.createInstance(); - if(isDestroyed){ return; } // Check if component is destroyed after every async - - cameraEnhancer = await (pCameraEnhancer || CameraEnhancer.createInstance(cameraView)); - if(isDestroyed){ return; } - - // Get default UI and append it to DOM. - cameraViewContainer.append(cameraView.getUIElement()); -} - -async beforeUnmount(){ - isDestroyed = true; - await pCameraEnhancer; - cameraEnhancer?.dispose(); - cameraEnhancer = null; -} - -// usage example in a tsx/jsx component -
-``` - -### Add [`CaptureVisionRouter`](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/capture-vision-router/capture-vision-router-module.html) - -To complete the code, we'll include the [`CaptureVisionRouter`](https://www.dynamsoft.com/capture-vision/docs/web/programming/javascript/api-reference/capture-vision-router/capture-vision-router-module.html) and handle it's life cycle similarly. - -```ts -import "../dynamsoft.config"; -import { CameraEnhancer, CameraView } from "dynamsoft-camera-enhancer"; -import { CaptureVisionRouter } from "dynamsoft-capture-vision-router"; - -let cameraEnhancer; -let pCameraEnhancer; // promise of cameraEnhancer -let cvRouter; -let pCvRouter; // promise of cvRouter -let isDestroyed = false; - -async mount(){ - // Create a `CameraEnhancer` instance for camera control and a `CameraView` instance for UI control. - const cameraView = await CameraView.createInstance(); - if(isDestroyed){ return; } // Check if component is destroyed after every async - - cameraEnhancer = await (pCameraEnhancer || CameraEnhancer.createInstance(cameraView)); - if(isDestroyed){ return; } - - // Get default UI and append it to DOM. - cameraViewContainer.append(cameraView.getUIElement()); - - // Create a `CaptureVisionRouter` instance and set `CameraEnhancer` instance as its image source. - cvRouter = await (pCvRouter || CaptureVisionRouter.createInstance()); - if(isDestroyed){ return; } - - cvRouter.setInput(cameraEnhancer); - - // Define a callback for results. - cvRouter.addResultReceiver({ onDecodedBarcodesReceived: (result) => { - if (!result.barcodeResultItems.length) return; - for (let item of result.barcodeResultItems) { - console.log(item.text); // output the decoded barcode text - } - }}); - - // Filter out unchecked and duplicate results. - const filter = new MultiFrameResultCrossFilter(); - // Filter out unchecked barcodes. - filter.enableResultCrossVerification("barcode", true); - // Filter out duplicate barcodes within 3 seconds. - filter.enableResultDeduplication("barcode", true); - await cvRouter.addResultFilter(filter); - if(isDestroyed){ return; } - - // Open camera and start scanning single barcode. - await cameraEnhancer.open(); - if(isDestroyed){ return; } - - await cvRouter.startCapturing("ReadSingleBarcode"); -} - -async beforeUnmount(){ - isDestroyed = true; - - await pCvRouter; - cvRouter?.dispose(); - cvRouter = null; - - await pCameraEnhancer; - cameraEnhancer?.dispose(); - cameraEnhancer = null; -} - -// usage example in a tsx/jsx component -
-``` - -### Final Notes - -Decoding video is slightly more complex than reading image, but by following the steps above, you can manage resources effectively and ensure your component runs smoothly. - -Again, if you don't want to go into detail, please refer to the [DBRJS sample](https://github.com/Dynamsoft/barcode-reader-javascript-samples/tree/main/hello-world) directly. - -Note that since we have taken over native rendering, avoid changing the UI through the framework within decoding video component; instead, make changes in its parent component. - -Once this component is rendered, decoding will start. You can control when decoding occurs by not rendering this component until needed.