<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>图片二维码识别</title>
<script src="./jsQR.js"></script>
<!-- <script src="https://cozmo.github.io/jsQR/jsQR.js"></script> -->
</head>
<body οnlοad="monted()">
<div id="imgDom"><video id="video" autoplay="autoplay"></video></div>
<canvas id="qrcanvas" style="display: none;"></canvas>
<img id="qrcanvasImg" style="display: none;"></canvas>
<span id='showCode'></span>
</body>
<script type="text/javascript">
var term = null;
/**
* 获取二维码地址
* @param {Object} url 二维码携带的地址信息
*/
const uploadCode = function(url) {
term && window.clearInterval(term);
document.getElementById('showCode').innerText = '识别结果:' + url.data;
document.getElementById('imgDom').style.display='none';
}
/**
* 截图并获取二维码
*/
const base64ToqR = function() {
// 截图存储画布
var canvas = document.getElementById("qrcanvas");
// 设置画布宽为视频的宽
canvas.width = video.videoWidth;
// 设置画布高为视频的高
canvas.height = video.videoHeight;
// 创建图片存储地址
var img = new Image();
// 设置画布高为视频的高
img.height = video.videoHeight;
// 设置图片宽为视频的宽
img.width = video.videoWidth;
var ctx = canvas.getContext("2d");
ctx.drawImage(video, 0, 0);
img.src = canvas.toDataURL('image/webp');
var imageData = ctx.getImageData(0, 0, img.width, img.height);
img.onload = function() {
// 图片转二维码信息
const code = jsQR(imageData.data, imageData.width, imageData.height, {
inversionAttempts: "dontInvert",
});
// 存在二维码信息调用二维码推送
code && uploadCode(code)
};
}
/**
* 播放或推送音频
*/
const playAudioToUser = function(stream) {
if ('srcObject' in video) {
video.srcObject = stream;
term = window.setInterval(base64ToqR, 1000);
} else {
video.src = URL.createObjectURL(stream);
}
}
/**
* 音视频获取失败
*/
const playAudioToUserError = function(error) {
console.log(error)
}
/**
* 基础资源加载完成
*/
const monted = function() {
navigator.getUserMedia({
video: true,
audio: false
}, playAudioToUser, playAudioToUserError);
}
注:外部环境需要使用Https协议
vue 相关放置掘金