web二维码识别

727 阅读1分钟

html布局区域代码

<head>
	<meta charset="utf-8" />
            <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0;" name="viewport" />
	<title>图片二维码识别</title>
	<!-- <script src="./jsQR.js"></script> -->
	<script src="https://cozmo.github.io/jsQR/jsQR.js"></script>
	<style type="text/css">
		* {
			margin: 0;
			padding: 0;
			border: 0;
			box-sizing: border-box;
		}

		html,
		body,
		#imgDom,#qrcanvasImg,#qrcanvas,video{
			width: 100vw;
			height:100vh;
			background-color: #000;
		}
		#showCode{
			line-height: 200px;
			font-size: 40px;
			color: #fff;
		}
	</style>
</head>
<body onload="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>`

javascript业务代码

<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: {
				facingMode: 'environment'
			},
			audio: false,
		}, playAudioToUser, playAudioToUserError);
	}
</script>