如何在React工程中使用JavaScript Barcode SDK建立Web条形码应用

基于WebAssembly构建的Dynamsoft JavaScript Barcode SDK让Web开发者可以建立适用于浏览器的高性能条码应用。这篇文章分享下如何使用React快速建立一个简单的Web条形码扫描应用。javascript

下载

Node.jscss

用React和JS Barcode SDK搭建HTML扫码应用

建立React应用:html

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

public/index.html中加载初始化JavaScript Barcode SDK.java

<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中建立一个组件:node

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中:react

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;

如今运行程序:git

yarn start

打开localhost:3000运行程序: <kbd>github

源码

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

相关文章
相关标签/搜索