基於WebAssembly構建的Dynamsoft JavaScript Barcode SDK讓Web開發者可以建立適用於瀏覽器的高性能條碼應用。這篇文章分享下如何使用React
快速建立一個簡單的Web條形碼掃描應用。javascript
Node.jscss
建立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瀏覽器