天天看點

使用getelementbyid給圖檔的路徑_如何在React工程中使用JavaScript Barcode SDK建立Web條形碼應用...

基于WebAssembly建構的Dynamsoft JavaScript Barcode SDK讓Web開發者能夠建立适用于浏覽器的高性能條碼應用。這篇文章分享下如何使用

React

快速建立一個簡單的Web條形碼掃描應用。

下載下傳

Node.js

用React和JS Barcode SDK搭建HTML掃碼應用

建立React應用:

npx create-react-app react-wasm-barcode
cd react-wasm-barcode
           

public/index.html

中加載初始化JavaScript Barcode SDK.

<img src="loading.gif" style="margin-top:10px" id="anim-loading">
    <script src="https://demo.dynamsoft.com/dbr_wasm/js/dbr-6.4.1.1.min.js"></script>
    <script>
      dynamsoft.dbrEnv.resourcesPath = 'https://demo.dynamsoft.com/dbr_wasm/js';
      dynamsoft.dbrEnv.onAutoLoadWasmSuccess = function () {
        window.reader = new dynamsoft.BarcodeReader();
        document.getElementById('anim-loading').style.display = 'none';
      };
      dynamsoft.dbrEnv.onAutoLoadWasmError = function (ex) {
        document.getElementById('anim-loading').style.display = 'none';
        alert('Fail to load the wasm file.');
      };
 
      //https://www.dynamsoft.com/CustomerPortal/Portal/TrialLicense.aspx
      dynamsoft.dbrEnv.licenseKey = "<Your Barcode License>";
</script>
           

這裡需要設定一個有效的license。如果沒有,可以注冊申請一個30天免費試用的。設定全局通路對象

window.reader

Barcode.js

中建立一個元件:

import React, { Component }from 'react';
export class Barcode extends Component {
    onChanged() {
        let image = document.getElementById('uploadImage').files[0];
        if (!image) {
            alert('Please add an image');
            return;
        }
        window.reader.decodeFileInMemory(image).then(function(results){
            var txts = [];
            for(var i=0;i<results.length;++i){
                txts.push(results[i].BarcodeText);
            }
            alert(txts.join("n"));
        }).catch(ex => {
            alert('error:' + (ex.message || ex));
        });
    }
   
    render() {
      return (
        <div>
          <input id="uploadImage" type="file" accept="image/bmp,image/jpeg,image/png,image/gif" onChange={this.onChanged}/>
        </div>
      );
    }
  }
           

這裡做的事情很簡單,通過系統對話框選擇一個圖檔檔案,然後識别圖像中的條形碼。

把這個元件導入到

App.js

中:

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import {Barcode} from './Barcode';
 
class App extends Component {
  render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <Barcode/>
        </header>
      </div>
    );
  }
}
export default App;
           

現在運作程式:

yarn start

打開localhost:3000運作程式:

使用getelementbyid給圖檔的路徑_如何在React工程中使用JavaScript Barcode SDK建立Web條形碼應用...

源碼

https://github.com/dynamsoft-dbr/javascript-barcode/tree/master/examples/react-wasm-barcode