基于WebAssembly构建的Dynamsoft JavaScript Barcode SDK让Web开发者能够创建适用于浏览器的高性能条码应用。这篇文章分享下如何使用React快速创建一个简单的Web条形码扫描应用。
下载
用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
来源:oschina
链接:https://my.oschina.net/u/1187419/blog/3002786