如何在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运行程序: <kbd>

源码

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

转载于:https://my.oschina.net/yushulx/blog/3002786

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值