二维码生成、解析

前端实现二维码的生成(根据输入文本生成二维码)和识别(上传图片解析二维码内容)的功能,基于常用且轻量的前端库来实现,方案简单易上手,无需复杂的构建配置。

实现思路

  • 二维码生成:使用 QRCode.js(轻量、无依赖、兼容性好),通过输入文本内容生成二维码并渲染到页面。
  • 二维码识别:使用 jsQR(纯前端解析二维码,无需后端),通过上传图片,将图片绘制到 Canvas 后解析像素数据,提取二维码内容。

完整实现代码

以下是开箱即用的代码,直接保存为 .html 文件即可运行:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>前端二维码生成与识别</title>
<style>
.container {
max-width: 600px;
margin: 20px auto;
padding: 20px;
font-family: Arial, sans-serif;
}
.section {
margin-bottom: 30px;
padding: 20px;
border: 1px solid #eee;
border-radius: 8px;
}
input, button {
padding: 8px 12px;
margin-right: 10px;
border: 1px solid #ddd;
border-radius: 4px;
}
button {
background: #409eff;
color: white;
border: none;
cursor: pointer;
}
button:hover {
background: #66b1ff;
}
#qrcode {
margin-top: 15px;
border: 1px solid #eee;
padding: 10px;
display: inline-block;
}
#scanResult {
margin-top: 15px;
padding: 10px;
border: 1px solid #eee;
min-height: 40px;
color: #333;
}
canvas {
display: none; /* 识别用的canvas隐藏 */
}
</style>
</head>
<body>
<div class="container">
<!-- 二维码生成区域 -->
<div class="section">
<h3>二维码生成</h3>
<input type="text" id="textInput" placeholder="请输入要生成二维码的内容" value="https://www.example.com">
<button id="generateBtn">生成二维码</button>
<div id="qrcode"></div>
</div>

<!-- 二维码识别区域 -->
<div class="section">
<h3>二维码识别</h3>
<input type="file" id="fileInput" accept="image/*">
<div id="scanResult">识别结果将显示在这里...</div>
</div>

<!-- 隐藏的canvas,用于识别二维码 -->
<canvas id="scanCanvas"></canvas>
</div>

<!-- 引入依赖库(CDN) -->
<script src="https://cdn.bootcdn.net/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/jsQR/1.4.0/jsQR.min.js"></script>

<script>
// ========== 二维码生成逻辑 ==========
const generateBtn = document.getElementById('generateBtn');
const textInput = document.getElementById('textInput');
const qrcodeContainer = document.getElementById('qrcode');

// 生成二维码函数
function generateQRCode(text) {
// 清空原有二维码
qrcodeContainer.innerHTML = '';
// 调用QRCode.js生成二维码
new QRCode(qrcodeContainer, {
text: text, // 二维码内容
width: 200, // 二维码宽度
colorDark: '#000000', // 深色块颜色
colorLight: '#ffffff', // 浅色块颜色
correctLevel: QRCode.CorrectLevel.H // 容错级别(H最高)
});
}

// 绑定生成按钮点击事件
generateBtn.addEventListener('click', () => {
const text = textInput.value.trim();
if (!text) {
alert('请输入要生成二维码的内容!');
return;
}
generateQRCode(text);
});

// 页面加载时默认生成一次
window.onload = () => {
generateQRCode(textInput.value.trim());
};

// ========== 二维码识别逻辑 ==========
const fileInput = document.getElementById('fileInput');
const scanResult = document.getElementById('scanResult');
const scanCanvas = document.getElementById('scanCanvas');
const ctx = scanCanvas.getContext('2d');

// 处理文件上传
fileInput.addEventListener('change', (e) => {
const file = e.target.files[0];
if (!file) return;

// 验证文件类型
if (!file.type.startsWith('image/')) {
scanResult.textContent = '请上传图片文件!';
return;
}

const reader = new FileReader();
reader.onload = (event) => {
const img = new Image();
img.onload = () => {
// 设置canvas尺寸与图片一致
scanCanvas.width = img.width;
scanCanvas.height = img.height;
// 将图片绘制到canvas
ctx.drawImage(img, 0, 0);
// 获取canvas像素数据
const imageData = ctx.getImageData(0, 0, img.width, img.height);
// 调用jsQR解析二维码
const code = jsQR(imageData.data, img.width, img.height);

if (code) {
scanResult.textContent = `识别成功:${code.data}`;
// 可选:输出二维码的位置信息
console.log('二维码位置:', code.location);
} else {
scanResult.textContent = '未识别到二维码,请确认图片包含清晰的二维码!';
}
};
img.src = event.target.result;
};
reader.readAsDataURL(file);
});
</script>
</body>
</html>

代码关键部分解释

  1. 二维码生成

    • 引入 QRCode.js 后,通过 new QRCode(容器DOM, 配置项) 生成二维码;
    • 核心配置:text(二维码内容)、width(尺寸)、correctLevel(容错级别,H级容错最高,适合二维码被部分遮挡的场景);
    • 每次生成前清空容器,避免重复渲染。
  2. 二维码识别

    • 引入 jsQR 后,需先将上传的图片绘制到 Canvas,因为 jsQR 需要基于像素数据解析;
    • jsQR(像素数据, 宽度, 高度) 返回解析结果:code.data 是二维码内容,code.location 是二维码在图片中的位置坐标;
    • 做了文件类型校验,避免上传非图片文件。

运行条件

  • 无需安装依赖,直接用浏览器打开 .html 文件即可(需联网,因为使用CDN加载库);
  • 兼容现代浏览器(Chrome、Firefox、Edge、Safari等),不支持IE低版本;
  • 识别时请上传清晰、无严重遮挡的二维码图片(推荐PNG/JPG格式)。

总结

  1. 前端生成二维码核心依赖 QRCode.js,通过简单配置即可快速渲染二维码到页面;
  2. 前端识别二维码核心依赖 jsQR,需将图片转为 Canvas 像素数据后解析;
  3. 整个方案纯前端实现,无需后端接口,轻量且易集成到现有项目。

如果需要集成到Vue/React等框架中,只需将核心逻辑(生成/识别函数)适配框架的语法即可,核心API用法不变。


二维码生成、解析
https://cszy.top/2018-08-29 二维码生成、解析-图片剪裁/
作者
csorz
发布于
2018年8月29日
许可协议