ZXing Browser

repository·master·Indexed 43 days ago

https://github.com/zxing-js/browser

A browser layer for the ZXing barcode processing library (version 0.2.1) that provides high-level APIs to scan barcodes from webcams, video elements, image elements, and URLs. It includes specialized readers for QR codes, Aztec, Data Matrix, PDF417, and 1D barcodes, as well as SVG writers for barcode generation.

Tokens
7.3K
Snippets
27
Records
34
Agent score
55%

What's inside ZXing

  1. Import @zxing/browser into your app

    master

    Depending on your module system, you can import the library using ES6 modules (synchronously or asynchronously), AMD, or UMD.

    <script type="module">
      import { BrowserQRCodeReader } from '@zxing/browser';
    
      const codeReader = new BrowserQRCodeReader();
    
      // do something with codeReader...
    </script>
  2. Install @zxing/browser

    master

    You can install the library using npm, yarn, or by including a script tag from a CDN like UNPKG.

    yarn add @zxing/browser
    npm i @zxing/browser
    <!-- loading ZXingBrowser via UNPKG -->
    <script type="text/javascript" src="https://unpkg.com/@zxing/browser@latest"></script>
  3. How IScannerControls works

    master

    When you start a continuous scan (using scan, decodeFromStream, etc.), the library returns an IScannerControls object. This object is your interface for managing the active scanning session.

    Key Methods:

    • stop(): Immediately stops the scanning loop and releases resources.
    • switchTorch(onOff: boolean): (Experimental) Toggles the device flashlight if supported.
    • streamVideoConstraintsApply(constraints, trackFilter?): Applies new constraints to the active video track.
    • streamVideoConstraintsGet(): Retrieves current constraints.
    • streamVideoSettingsGet(): Retrieves current settings (e.g., brightness, zoom).
    • streamVideoCapabilitiesGet(): Retrieves available capabilities of the track.
  4. Scan from video or image URLs

    master

    Use decodeFromImageUrl to scan a static image from a URL, or decodeFromVideoUrl to scan a video source from a URL.

    const codeReader = new ZXingBrowser.BrowserQRCodeReader();
    
    const source = 'https://my-image-or-video/01.png';
    const resultImage = await codeReader.decodeFromImageUrl(source);
    // or use decodeFromVideoUrl for videos
    const resultVideo = await codeReader.decodeFromVideoUrl(source);
  5. Scan barcodes from a webcam

    master

    To perform continuous scanning from a webcam, use decodeFromVideoDevice. This method runs and decodes barcodes until you call controls.stop(). You can also use decodeOnceFromVideoDevice if you only want to await the first detected barcode.

    const codeReader = new BrowserQRCodeReader();
    
    const videoInputDevices = await ZXingBrowser.BrowserCodeReader.listVideoInputDevices();
    
    // choose your media device (webcam, frontal camera, back camera, etc.)
    const selectedDeviceId = videoInputDevices[0].deviceId;
    
    console.log(`Started decode from camera with id ${selectedDeviceId}`);
    
    const previewElem = document.querySelector('#test-area-qr-code-webcam > video');
    
    // you can use the controls to stop() the scan or switchTorch() if available
    const controls = await codeReader.decodeFromVideoDevice(selectedDeviceId, previewElem, (result, error, controls) => {
      // use the result and error values to choose your actions
      // you can also use controls API in this scope like the controls
      // returned from the method.
    });
    
    // stops scanning after 20 seconds
    setTimeout(() => controls.stop(), 20000);
  6. Scan from HTML video or image elements

    master

    Use decodeFromImageElement to scan an existing <img> element in the DOM, or decodeFromVideoElement to scan an existing <video> element.

    const codeReader = new ZXingBrowser.BrowserQRCodeReader();
    const sourceElem = document.querySelector('#my-image-id');
    const resultImage = await codeReader.decodeFromImageElement(sourceElem);
    // or use decodeFromVideoElement for videos
    const resultVideo = await codeReader.decodeFromVideoElement(sourceElem);
  7. Configure IBrowserCodeReaderOptions

    master

    When initializing a browser code reader, you can provide an optional configuration object implementing the IBrowserCodeReaderOptions interface to fine-tune scanning behavior and video playback timeouts.

    Available options:

    • delayBetweenScanSuccess: A number representing the delay time (in milliseconds) between subsequent successful decode results. Use this to prevent the scanner from emitting the same result too rapidly.
    • delayBetweenScanAttempts: A number representing the delay time (in milliseconds) between individual decode attempts made by the scanner. Increasing this can reduce CPU usage.
    • tryPlayVideoTimeout: A number representing the timeout (in milliseconds) for waiting for the video 'canplay' event before failing.
    const options: IBrowserCodeReaderOptions = {
      delayBetweenScanSuccess: 1000,
      delayBetweenScanAttempts: 500,
      tryPlayVideoTimeout: 5000
    };
  8. List of available Browser Readers

    master

    The library provides specialized reader classes for different barcode formats. While BrowserCodeReader is the base class, you should typically use one of the specialized subclasses for convenience.

    - `BrowserAztecCodeReader`
    - `BrowserCodeReader` (base class, requires a `Reader` instance — use a subclass for convenience)
    - `BrowserDatamatrixCodeReader`
    - `BrowserMultiFormatOneDReader`
    - `BrowserMultiFormatReader` (2D + 1D)
    - `BrowserPDF417Reader`
    - `BrowserQRCodeReader`
  9. Available BrowserCodeReader scan methods

    master

    The BrowserCodeReader family provides several methods for decoding barcodes in the browser. These are categorized into continuous scanning and 'once' scanning (detecting a single barcode and resolving).

    Continuous Scanning:

    • decodeFromCanvas
    • decodeFromImageElement
    • decodeFromImageUrl
    • decodeFromConstraints
    • decodeFromStream
    • decodeFromVideoDevice
    • decodeFromVideoElement
    • decodeFromVideoUrl

    Single Detection ('Once'):

    • decodeOnceFromConstraints
    • decodeOnceFromStream
    • decodeOnceFromVideoDevice
    • decodeOnceFromVideoElement
    • decodeOnceFromVideoUrl
  10. Configure possible barcode formats in BrowserCodeReader

    master

    You can restrict the types of barcodes the decoder searches for by setting the possibleFormats property. This is useful for improving performance or accuracy by narrowing the search space during a scan.

    Set this property using an array of BarcodeFormat values.

    // Example: Only look for QR Codes
    reader.possibleFormats = [BarcodeFormat.QR_CODE];
  11. Control scanning state with IScannerControls

    master

    The IScannerControls interface provides methods to manage an active scanning session. The primary stable method is stop(), which terminates the scanning process loop.

    Note that several other methods related to torch control and media stream constraints are marked as @experimental and are considered highly unstable. Use them at your own risk, especially switchTorch as browser support is not yet ready.

    // Example of stopping a scan
    // Assuming 'controls' is an instance of IScannerControls
    controls.stop();
  12. List available video input devices

    master

    Use listVideoInputDevices() to get a list of all available cameras on the user's device. This is useful for allowing users to select a specific camera (e.g., switching between front and back cameras).

    Returns a Promise<MediaDeviceInfo[]>.

    const devices = await BrowserCodeReader.listVideoInputDevices();
    devices.forEach(device => {
      console.log(`Device: ${device.label} (ID: ${device.deviceId})`);
    });