1. 程式人生 > 其它 >掃描二維碼 從相機掃描識別不到的問題

掃描二維碼 從相機掃描識別不到的問題

掃描二維碼 從相機掃描識別不到的問題

前言

最近做了一個掃描二維碼的專案 要求可以從相簿中掃描 做出來之後 發現從相掃描二維碼時好時壞
後來發現了原因

原因

原因盡然不是程式碼的問題 也不是環境的問題
而是!!!!
二維碼在頁面中太大了!!!!!!
這樣會導致識別的時候不能識別到完整的整個二維碼
所以 二維碼在頁面中要小一點
不好:

程式碼

import React, { PureComponent } from 'react';
let barcode = null
export default class scanPage extends PureComponent {
  // plus準備工作
  componentDidMount() {
    if (window.plus) {
      this.plusReady();
    } else {
      document.addEventListener('plusready', this.plusReady, false);
    }
  }
  // 解除安裝元件時 釋放掃碼元件資源
  componentWillUnmount() {
    barcode&&barcode.close();
    barcode = null;
  }
  // plusReady h5+必備
  plusReady = () => {
    // 在這裡呼叫plus api
    this.creatBarCode()
  }
  // 建立barcode控制元件
  creatBarCode() {
    if (!barcode) {
      barcode = plus.barcode.create('barcode', [plus.barcode.QR], {
        background: '#fff',
        frameColor: '#07c160',
        scanbarColor: '#07c160',
        top: '100px',
        left: '0px',
        width: '100%',
        height: '580px',
        position: 'static'
      });
      barcode.onmarked = this.onmarked//掃碼成功
      barcode.onerror = this.onerror//掃碼失敗
      plus.webview.currentWebview().append(barcode);//必要的
    }
    barcode.start();
  }
  // 識別成功
  onmarked(type, result) {
    alert('掃描結果:' + result)
  }
  // 識別失敗
  onerror(err){
    alert("掃碼失敗");
    console.log('掃碼失敗',JSON.stringify(err)) 
    barcode&&barcode.close();
    barcode = null;
  }
  // 從相簿中選擇
  scanFromPic() {
    let that=this
    plus.gallery.pick(function (path) {
      plus.barcode.scan(path, that.onmarked, that.onerror);
    }, function (err) {
      alert('選擇相片失敗: ' + JSON.stringify(err.message));
    });
  }
  render() {
    return (
      <div >
        <div style={{marginTop:70+'px',textAlign:'right'}} onClick={this.scanFromPic.bind(this)}>從相簿選擇</div>
        <div id="barcode"></div>
      </div>
    )
  }
}