1. 程式人生 > >如何利用Web Worker優化網頁條碼識別應用

如何利用Web Worker優化網頁條碼識別應用

現在主流的瀏覽器都支援WebRTC,通過getUserMedia可以在瀏覽器中輕鬆開啟攝像頭。Web開發者可以使用JavaScript開發網頁版的條碼掃描應用。通過Chrome和Safari的測試發現,當JS程式碼耗時多的時候,Chrome中的視訊依然流暢,而Safari出現嚴重卡頓。推測Chrome的視訊渲染和JavaScript不在一條執行緒中,不過如果要通過canvas來繪製UI依然會出現卡頓。要解決這個問題,可以把耗時多,計算量大的程式碼放到web worker中。

使用Web Worker載入執行JavaScript條形碼識別庫

條形碼的檢測介面可能會消耗幾百毫秒的時間,所以把這部分放到web worker中。這裡用到了

Dynamsoft WebAssembly Barcode SDK.

建立worker.js並匯入JavaScript條形碼識別庫:

function browserRedirect() {
    var deviceType;
    var sUserAgent = navigator.userAgent.toLowerCase();
    var bIsIpad = sUserAgent.match(/ipad/i) == "ipad";
    var bIsIphoneOs = sUserAgent.match(/iphone os/i) == "iphone os";
    var
bIsMidp = sUserAgent.match(/midp/i) == "midp"; var bIsUc7 = sUserAgent.match(/rv:1.2.3.4/i) == "rv:1.2.3.4"; var bIsUc = sUserAgent.match(/ucweb/i) == "ucweb"; var bIsAndroid = sUserAgent.match(/android/i) == "android"; var bIsCE = sUserAgent.match(/windows ce/i) == "windows ce"; var bIsWM = sUserAgent.match(/windows mobile/i
) == "windows mobile"; if (bIsIpad || bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM) { deviceType = 'phone'; } else { deviceType = 'pc'; } return deviceType; } if (browserRedirect() === 'pc') { importScripts('https://demo.dynamsoft.com/dbr_wasm/js/dbr-6.3.0.1.min.js'); } else { importScripts('https://demo.dynamsoft.com/dbr_wasm/js/dbr-6.3.0.1.mobile.min.js'); }

由於桌面和移動裝置在效能上有差距,可以載入不同的版本。

初始化條碼識別庫:

var reader;
var dynamsoft = self.dynamsoft || {};
dynamsoft.dbrEnv = dynamsoft.dbrEnv || {};
dynamsoft.dbrEnv.resourcesPath = 'https://demo.dynamsoft.com/dbr_wasm/js/';

dynamsoft.dbrEnv.onAutoLoadWasmSuccess = function () {
    reader = new dynamsoft.BarcodeReader();
    postMessage({
        event: "onload",
        body: "Successfully loaded wasm."
    });
};
dynamsoft.dbrEnv.onAutoLoadWasmError = function (status) {
    postMessage({
        event: "onerror",
        body: "Failed to load wasm."
    });
};
//https://www.dynamsoft.com/CustomerPortal/Portal/TrialLicense.aspx
dynamsoft.dbrEnv.licenseKey = "t0068MgAAAD2IrA1WJjiVx78RfaZ46qMyCY8DaqpvAD57z5QWkwVQkVwZEf7lE+M2QYbnPx9Fu/aFvCL1mz0Kh2YK0milUng=";

識別解碼JS主執行緒傳送過來的視訊影象:

onmessage = function (e) {
    e = e.data;
    switch (e.type) {
        case "decodeBuffer":
            {
                self.reader.decodeBuffer(e.body, e.width, e.height, e.width * 4, dynamsoft.BarcodeReader.EnumImagePixelFormat.IPF_ARGB_8888).then(results => {
                    postMessage({
                        event: 'onresult',
                        body: results
                    });
                }).catch(ex => {
                    postMessage({
                        event: 'onresult',
                        body: 'No barcode detected'
                    });
                });
                break;
            }
        default:
            break;
    }
};

在主執行緒中獲取傳送視訊幀:

function scanBarcode() {

  let context = ctx,
    width = videoWidth,
    height = videoHeight;

  context.drawImage(videoElement, 0, 0, width, height);
  var barcodeCanvas = document.createElement("canvas");
  barcodeCanvas.width = width;
  barcodeCanvas.height = height;
  var barcodeContext = barcodeCanvas.getContext('2d');
  barcodeContext.drawImage(videoElement, 0, 0, width, height);
  // read barcode
  if (myWorker) {
    myWorker.postMessage({
      type: 'decodeBuffer',
      body: barcodeContext.getImageData(0, 0, width, height).data,
      width: width,
      height: height
    });
  }
}

最後把結果畫出來:

function 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);
}

在瀏覽器中的執行效果:

瀏覽器條形碼識別

Source Code