行者豆児 發表於 2024-2-23 16:09:00

vue3 使用 html5-qrcode 实现扫描二维码功能

<h3 id="1-安装">1. 安装</h3>
<p>npm安装</p>
<pre><code>npm install --save-dev html5-qrcode
</code></pre>
<p>或直接引入</p>
<pre><code>&lt;script src="https://unpkg.com/html5-qrcode" type="text/javascript"&gt;
</code></pre>
<h3 id="2-引入">2. 引入</h3>
<ol>
<li>根据需求自定义渲染 QR scanning UI 的容器。</li>
</ol>
<pre><code>&lt;div id="reader" width="600px"&gt;&lt;/div&gt;
</code></pre>
<ol start="2">
<li>引入 Html5Qrcode</li>
</ol>
<pre><code>// 简单模式(使用默认用户界面)
import {Html5QrcodeScanner} from "html5-qrcode";
// 专业模式(使用自己的用户界面)
import {Html5Qrcode} from "html5-qrcode";
</code></pre>
<blockquote>
<p><code>Html5QrcodeScanner</code>允许您使用几行代码和默认用户界面实现端到端扫描仪,该用户界面允许使用相机进行扫描或从文件系统中选择图像。<br>
<code>Html5Qrcode</code>类用来设置 QR 码扫描仪(使用您自己的用户界面),并允许用户使用相机或通过选择文件系统中的图像文件或智能手机中的本机相机来扫描 QR 码。</p>
</blockquote>
<h3 id="3-使用">3. 使用</h3>
<ol>
<li>如果使用 <code>Html5QrcodeScanner</code>,系统默认</li>
</ol>
<pre><code>// 扫描成功
function onScanSuccess(decodedText, decodedResult) {
console.log(`Code matched = ${decodedText}`, decodedResult);
}
// 扫描失败
function onScanFailure(error) {
console.warn(`Code scan error = ${error}`);
}
// 创建并配置实例,渲染扫描仪
let html5QrcodeScanner = new Html5QrcodeScanner(
"reader",
{ fps: 10, qrbox: {width: 250, height: 250} },
/* verbose= */ false);
html5QrcodeScanner.render(onScanSuccess, onScanFailure);
</code></pre>
<ol start="2">
<li>如果使用 <code>Html5Qrcode</code>,自定义</li>
</ol>
<p>获取相机id</p>
<pre><code>// 获取支持的相机列表
Html5Qrcode.getCameras().then(devices =&gt; {
/**
   * devices 类型为对象数组
   * { id: "id", label: "label" }
   */
if (devices &amp;&amp; devices.length) {
    let cameraId = devices.id;
    // 开始扫描
}
}).catch(err =&gt; {
// 处理错误
});
</code></pre>
<blockquote>
<p>注意:如果未授予相机权限,会触发权限请求申请。<br>
使用相机需要网站使用https协议, vite 本地开启 https 调试参考随笔</p>
</blockquote>
<p>开始扫码</p>
<pre><code>// 开始扫码
const html5QrCode = new Html5Qrcode(/* element id */ "reader");
html5QrCode.start(
cameraId,
{
    fps: 10,    // 帧率,控制扫描速度
    qrbox: { width: 250, height: 250 }// 限制要用于扫描的取景器区域
},
(decodedText, decodedResult) =&gt; {
    // 获取扫描结果
},
(errorMessage) =&gt; {
    // 结果错误处理
})
.catch((err) =&gt; {
// 无法扫描时的错误处理
});
</code></pre>
<blockquote>
<p>您可以选择在构造函数中设置另一个参数,以verbose将所有日志打印到控制台<br>
<code>const html5QrCode = new Html5Qrcode("reader", /* verbose= */ true);</code></p>
</blockquote>
<p>停止</p>
<pre><code>html5QrCode.stop().then((ignore) =&gt; {
// 停止扫描
}).catch((err) =&gt; {
// 停止失败处理
});
</code></pre>
<blockquote>
<p>其它相关配置<br>
<img src="https://img2024.cnblogs.com/blog/1857566/202402/1857566-20240223153325436-1751554591.png" alt="image" loading="lazy"></p>
</blockquote>
<h3 id="4-完整示例">4. 完整示例</h3>
<p>页面</p>
<pre><code>&lt;template&gt;
&lt;div class="page-box"&gt;
    &lt;div class="qr-container"&gt;
      &lt;div class="qr-box"&gt;
      &lt;div id="reader"&gt;&lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;
    &lt;div class="btn-box"&gt;
      &lt;div&gt;
      &lt;van-icon name="arrow-left" @click="clickBack" /&gt;
      &lt;/div&gt;
      &lt;div&gt;
      &lt;van-uploader
          v-model="state.fileList"
          :preview-image="false"
          :after-read="uploadImg"
      &gt;
          &lt;van-icon name="photo-o"
      /&gt;&lt;/van-uploader&gt;
      &lt;/div&gt;
    &lt;/div&gt;
&lt;/div&gt;
&lt;/template&gt;

&lt;style scoped&gt;
.page-box {
display: flex;
flex-direction: column;
height: 100%;
background: #000;
}
.qr-container {
position: relative;
width: 100%;
height: 90%;
}
.qr-box {
height: 100%;
}
#reader {
top: 50%;
left: 0;
}
.btn-box {
flex: 1;
display: flex;
justify-content: space-around;
align-items: flex-start;
margin-top: auto;
padding: 12px;
color: #fff;
font-size: 28px;
}
&lt;/style&gt;
</code></pre>
<p>逻辑</p>
<pre><code>&lt;script setup&gt;
import { reactive, onMounted, onUnmounted } from "vue";
import { Html5Qrcode } from "html5-qrcode";
import { showToast } from "vant";

import useVueRouter from "@/hooks/useRouter";
const { goBack } = useVueRouter();

const state = reactive({
html5QrCode: null,
fileList: [],
});

onMounted(() =&gt; {
getCamerasInfo();
});
onUnmounted(() =&gt; {
if (state.html5QrCode?.isScanning) {
    stopScan();
}
});

const clickBack = () =&gt; {
goBack();
};

const getCamerasInfo = () =&gt; {
Html5Qrcode.getCameras()
    .then((devices) =&gt; {
      if (devices &amp;&amp; devices.length) {
      state.html5QrCode = new Html5Qrcode("reader");
      startScan();
      }
    })
    .catch((err) =&gt; {
      showToast({
      message: "摄像头无访问权限!",
      duration: 2000,
      });
    });
};

const startScan = () =&gt; {
state.html5QrCode
    .start(
      { facingMode: "environment" },
      {
      fps: 1,
      qrbox: { width: 250, height: 250 },
      },
      (decodedText, decodedResult) =&gt; {
      showToast(decodedText, decodedResult);
      }
    )
    .catch((err) =&gt; {
      console.log("扫码失败", err);
    });
};

const stopScan = () =&gt; {
state.html5QrCode
    .stop()
    .then((a) =&gt; {
      console.log("已停止扫码", a);
    })
    .catch((err) =&gt; {
      console.log(err);
      showToast("停止失败");
    });
};

const uploadImg = () =&gt; {
try {
    window.qrcode.callback = (result) =&gt; {
      showToast(result);
    };
    let file = state.fileList.file;
    let reader = new FileReader();
    reader.onload = (function () {
      return function (e) {
      window.qrcode.decode(e.target.result);
      };
    })(file);
    reader.readAsDataURL(file);
} catch (error) {
    console.log(error);
    showToast({
      message: "识别失败!",
      duration: 2000,
    });
}
};
&lt;/script&gt;
</code></pre>
<h3 id="5-相关链接">5. 相关链接</h3>
<p>GitHub地址<br>
官方教程<br>
qrcode.minhazav.dev<br>
vite 本地开启 https</p><br><br>
来源:https://www.cnblogs.com/lpkshuai/p/18029808
頁: [1]
查看完整版本: vue3 使用 html5-qrcode 实现扫描二维码功能