如何用React, Webcam和JS Barcode SDK创建Web扫码App

这篇文章分享下如何结合React WebcamDynamsoft JavaScript Barcode SDK来创建Web扫码App。

Web实时扫码

从GitHub上下载react-webcam.js放到React工程中。 打开这个JS文件。在render()函数中添加一个buttoncanvas:

render() {
    return (
      <div id='videoview' width={this.props.width} height={this.props.height}>
        <button onClick={this.scanBarcode}>Scan Barcodes</button>
        <video
          autoPlay
          width={this.props.width}
          height={this.props.height}
          src={this.state.src}
          muted={this.props.audio}
          className={this.props.className}
          playsInline
          style={this.props.style}
          ref={(ref) => {
            this.video = ref;
          }}
        />
        <canvas id="overlay" width={this.props.width} height={this.props.height}></canvas>
      </div>
    );
  }

button用于触发扫码,canva用来绘制显示结果。为了让结果显示在video上方,创建一个react-webcam.css调整下布局:

#videoview {
    position: relative;
    width: 640px;
    height: 480px;
  }
 
#video {
    position: relative;
    width: 100%;
    height: 100%;
    z-index: 1
}
 
#overlay {
    position: absolute;
    top: 100;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 2
}

react-webcam.js中导入这个CSS文件:

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import './react-webcam.css';

创建button的响应事件scanBarcode()。函数触发时,先把video绘制到一个临时canvas上。然后得到图像数据传入barcode解码接口中:

scanBarcode() {
    if (window.reader) {
      let canvas = document.createElement('canvas');
      canvas.width = this.props.width;
      canvas.height = this.props.height
      let ctx = canvas.getContext('2d');
      ctx.drawImage(this.video, 0, 0, this.props.width, this.props.height);
     
      window.reader.decodeBuffer(
        ctx.getImageData(0, 0, canvas.width, canvas.height).data,
        canvas.width,
        canvas.height,
        canvas.width * 4,
        window.dynamsoft.BarcodeReader.EnumImagePixelFormat.IPF_ARGB_8888
      )
      .then((results) => {
        this.showResults(results);
      });
    }
     
  }

构造函数中需要绑定this。如果不绑定,thisbutton点击的时候无法使用:

constructor() {
    super();
    this.state = {
      hasUserMedia: false,
    };
 
    this.scanBarcode = this.scanBarcode.bind(this);
  }

扫描触发之后需要持续调用scanBarcode(),并把结果显示在video上:

showResults(results) {
    let context = this.clearOverlay();
    let txts = [];
    try {
      let localization;
      for (var i = 0; i < results.length; ++i) {
        if (results[i].LocalizationResult.ExtendedResultArray[0].Confidence >= 30) {
          txts.push(results[i].BarcodeText);
          localization = results[i].LocalizationResult;
          this.drawResult(context, localization, results[i].BarcodeText);
        }
      }
       
      this.scanBarcode();
       
    } catch (e) {
      this.scanBarcode();
    }
  }
 
clearOverlay() {
    let context = document.getElementById('overlay').getContext('2d');
    context.clearRect(0, 0, this.props.width, this.props.height);
    context.strokeStyle = '#ff0000';
    context.lineWidth = 5;
    return context;
  }
   
drawResult(context, localization, text) {
    context.beginPath();
    context.moveTo(localization.X1, localization.Y1);
    context.lineTo(localization.X2, localization.Y2);
    context.lineTo(localization.X3, localization.Y3);
    context.lineTo(localization.X4, localization.Y4);
    context.lineTo(localization.X1, localization.Y1);
    context.stroke();
   
    context.font = '18px Verdana';
    context.fillStyle = '#ff0000';
    let x = [ localization.X1, localization.X2, localization.X3, localization.X4 ];
    let y = [ localization.Y1, localization.Y2, localization.Y3, localization.Y4 ];
    x.sort(function(a, b) {
      return a - b;
    });
    y.sort(function(a, b) {
      return b - a;
    });
    let left = x[0];
    let top = y[0];
   
    context.fillText(text, left, top + 50);
  }

public/index.html中加载dbr-6.4.1.3.min.js文件,并创建可用于全局访问的window.reader

<body>
    <img src="loading.gif" style="margin-top:10px" id="anim-loading">
    <script src="https://demo.dynamsoft.com/dbr_wasm/js/dbr-6.4.1.3.min.js"></script>
    <script>
      dynamsoft.dbrEnv.resourcesPath = 'https://demo.dynamsoft.com/dbr_wasm/js';
      dynamsoft.dbrEnv.onAutoLoadWasmSuccess = function () {
        window.reader = new dynamsoft.BarcodeReader();
        window.dynamsoft = dynamsoft;
        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.');
      };
      dynamsoft.dbrEnv.bUseWorker = true;
 
      // Get a free trial license from https://www.dynamsoft.com/CustomerPortal/Portal/TrialLicense.aspx
      dynamsoft.dbrEnv.licenseKey = "Your Barcode SDK License"
 
    </script>
    <div id="root"></div>

这里必须把dynamsoft.dbrEnv.bUseWorker设置成true。只有使用了web worker,主线程才不会因为条形码识别耗时而卡住。

App.js中添加React Webcam

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

运行程序:

npm start

在浏览器中访问localhost:3000

源码

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值