-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathqr-code-decoder.html
More file actions
675 lines (605 loc) · 23.9 KB
/
Copy pathqr-code-decoder.html
File metadata and controls
675 lines (605 loc) · 23.9 KB
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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="免费在线二维码识别器,支持上传图片、拖拽、剪贴板粘贴和摄像头扫码。">
<meta name="keywords" content="二维码, QR码, 二维码识别, 二维码扫描, 摄像头扫码, QR Code Decoder">
<meta name="author" content="Simon Willison">
<meta name="date" content="2026-06-22">
<title>二维码识别器</title>
<script src="https://cdn.jsdelivr.net/npm/jsqr@1.4.0/dist/jsQR.min.js"></script>
<style>
* {
box-sizing: border-box;
}
body {
font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
line-height: 1.5;
}
h1 {
margin-top: 0;
}
/* Mode toggle buttons */
.mode-toggle {
display: flex;
gap: 10px;
margin-bottom: 20px;
}
.mode-btn {
flex: 1;
padding: 12px 20px;
border: 2px solid #666;
background: white;
border-radius: 8px;
font-size: 16px;
font-weight: bold;
cursor: pointer;
transition: all 0.2s;
}
.mode-btn:hover {
border-color: #333;
background: #f5f5f5;
}
.mode-btn.active {
background: #007bff;
border-color: #007bff;
color: white;
}
/* Drop area */
#dropArea {
border: 3px dashed #666;
border-radius: 12px;
width: 100%;
min-height: 200px;
margin: 0 auto 20px;
padding: 20px;
text-align: center;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
cursor: pointer;
transition: border-color 0.2s, background-color 0.2s;
}
#dropArea:hover {
border-color: #333;
background-color: rgba(0, 0, 0, 0.05);
}
#dropArea.highlight {
border-color: #0066cc;
background-color: rgba(0, 102, 204, 0.1);
}
.dropzone-text {
font-size: 18px;
color: #444;
}
.dropzone-hint {
font-size: 14px;
color: #888;
margin-top: 8px;
}
#fileElem {
display: none;
}
/* Webcam container */
.webcam-container {
display: none;
width: 100%;
margin-bottom: 20px;
}
.webcam-container.active {
display: block;
}
.video-wrapper {
position: relative;
overflow: hidden;
border-radius: 8px;
background: #000;
touch-action: none;
max-height: 400px;
}
#webcam-video {
width: 100%;
max-height: 400px;
display: block;
background: #000;
object-fit: cover;
transform-origin: center center;
transition: transform 0.05s ease-out;
}
.zoom-hint {
position: absolute;
bottom: 10px;
left: 50%;
transform: translateX(-50%);
background: rgba(0, 0, 0, 0.6);
color: white;
padding: 4px 10px;
border-radius: 4px;
font-size: 12px;
pointer-events: none;
opacity: 0;
transition: opacity 0.3s;
}
.video-wrapper:active .zoom-hint {
opacity: 1;
}
.webcam-placeholder {
width: 100%;
height: 300px;
background: #f0f0f0;
border-radius: 8px;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
color: #666;
}
.webcam-placeholder-icon {
font-size: 48px;
margin-bottom: 10px;
}
/* Webcam controls */
.webcam-bottom-controls {
display: none;
}
.webcam-bottom-controls.active {
display: block;
}
.webcam-controls {
display: flex;
gap: 10px;
margin-top: 10px;
flex-wrap: wrap;
}
.webcam-btn {
padding: 10px 16px;
border: none;
border-radius: 6px;
font-size: 14px;
font-weight: bold;
cursor: pointer;
transition: background-color 0.2s;
}
.webcam-btn.start {
background: #28a745;
color: white;
}
.webcam-btn.start:hover {
background: #218838;
}
.webcam-btn.stop {
background: #dc3545;
color: white;
}
.webcam-btn.stop:hover {
background: #c82333;
}
.webcam-btn.switch {
background: #6c757d;
color: white;
}
.webcam-btn.switch:hover {
background: #5a6268;
}
.webcam-btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.webcam-status {
text-align: center;
padding: 10px;
font-size: 14px;
color: #666;
}
/* Result area */
#result {
margin-top: 20px;
padding: 16px;
border: 1px solid #ccc;
border-radius: 5px;
white-space: pre-wrap;
word-break: break-word;
line-height: 1.5;
}
#result:empty {
display: none;
}
#result a {
color: #0066cc;
}
.copy-result-btn {
margin-top: 10px;
padding: 8px 16px;
border: 1px solid #007bff;
background: #fff;
color: #007bff;
border-radius: 5px;
cursor: pointer;
font-size: 14px;
transition: all 0.2s;
}
.copy-result-btn:hover {
background: #007bff;
color: #fff;
}
.copy-result-btn.copied {
background: #28a745;
border-color: #28a745;
color: #fff;
}
</style>
</head>
<body>
<h1>二维码识别</h1>
<p>基于 <a href="https://github.com/cozmo/jsQR/">jsQR</a> 实现,纯前端识别,图片不会上传到服务器。</p>
<div class="mode-toggle">
<button class="mode-btn active" id="image-mode-btn">图片识别</button>
<button class="mode-btn" id="webcam-mode-btn">摄像头识别</button>
</div>
<div id="dropArea">
<input type="file" id="fileElem" accept="image/*">
<div class="dropzone-text">拖拽图片到此处,或点击选择文件</div>
<div class="dropzone-hint">也支持从剪贴板粘贴图片(Ctrl/Cmd + V)</div>
</div>
<div class="webcam-container" id="webcam-container">
<div class="webcam-placeholder" id="webcam-placeholder">
<div class="webcam-placeholder-icon">📹</div>
<div>点击“开启摄像头”开始扫码</div>
</div>
<div class="video-wrapper" id="video-wrapper" style="display: none;">
<video id="webcam-video" autoplay playsinline></video>
<div class="zoom-hint" id="zoom-hint">双指捏合缩放</div>
</div>
</div>
<div id="result"></div>
<button type="button" id="copy-result-btn" class="copy-result-btn" style="display: none;">复制识别结果</button>
<div class="webcam-bottom-controls" id="webcam-bottom-controls">
<div class="webcam-controls">
<button class="webcam-btn start" id="start-camera-btn">开启摄像头</button>
<button class="webcam-btn stop" id="stop-camera-btn" style="display: none;">关闭摄像头</button>
<button class="webcam-btn switch" id="switch-camera-btn" style="display: none;">切换摄像头</button>
</div>
<div class="webcam-status" id="webcam-status"></div>
</div>
<script>
// Ensure jsQR is loaded before proceeding
window.onload = function() {
if (typeof jsQR === 'undefined') {
document.getElementById('result').innerHTML = "错误:QR 码识别库加载失败,请检查网络连接后刷新页面。";
return;
}
const dropArea = document.getElementById('dropArea');
const fileElem = document.getElementById('fileElem');
const result = document.getElementById('result');
const copyResultBtn = document.getElementById('copy-result-btn');
let currentResult = '';
// Mode toggle elements
const imageModeBtn = document.getElementById('image-mode-btn');
const webcamModeBtn = document.getElementById('webcam-mode-btn');
const webcamContainer = document.getElementById('webcam-container');
const webcamBottomControls = document.getElementById('webcam-bottom-controls');
// Webcam elements
const webcamVideo = document.getElementById('webcam-video');
const webcamPlaceholder = document.getElementById('webcam-placeholder');
const videoWrapper = document.getElementById('video-wrapper');
const zoomHint = document.getElementById('zoom-hint');
const startCameraBtn = document.getElementById('start-camera-btn');
const stopCameraBtn = document.getElementById('stop-camera-btn');
const switchCameraBtn = document.getElementById('switch-camera-btn');
const webcamStatus = document.getElementById('webcam-status');
let currentMode = 'image';
let webcamStream = null;
let scanInterval = null;
let currentFacingMode = 'environment';
let hasMultipleCameras = false;
// Pinch-to-zoom state
let currentScale = 1;
let initialDistance = null;
let initialScale = 1;
// --- Image mode handlers (existing functionality) ---
['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
dropArea.addEventListener(eventName, preventDefaults, false);
});
function preventDefaults(e) {
e.preventDefault();
e.stopPropagation();
}
['dragenter', 'dragover'].forEach(eventName => {
dropArea.addEventListener(eventName, highlight, false);
});
['dragleave', 'drop'].forEach(eventName => {
dropArea.addEventListener(eventName, unhighlight, false);
});
function highlight(e) {
dropArea.classList.add('highlight');
}
function unhighlight(e) {
dropArea.classList.remove('highlight');
}
dropArea.addEventListener('click', () => fileElem.click());
dropArea.addEventListener('drop', handleDrop, false);
fileElem.addEventListener('change', handleFiles, false);
document.addEventListener('paste', handlePaste, false);
function handleDrop(e) {
const dt = e.dataTransfer;
const files = dt.files;
handleFiles(files);
}
function handleFiles(files) {
const file = files instanceof FileList ? files[0] : this.files[0];
if (file) {
decodeQR(file);
}
}
function handlePaste(e) {
const items = e.clipboardData.items;
for (let i = 0; i < items.length; i++) {
if (items[i].type.indexOf('image') !== -1) {
const blob = items[i].getAsFile();
decodeQR(blob);
break;
}
}
}
function decodeQR(file) {
const reader = new FileReader();
reader.onload = function(e) {
const img = new Image();
img.onload = function() {
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
canvas.width = img.width;
canvas.height = img.height;
context.drawImage(img, 0, 0, img.width, img.height);
const imageData = context.getImageData(0, 0, canvas.width, canvas.height);
const code = jsQR(imageData.data, imageData.width, imageData.height);
if (code) {
const decoded = decodeQRData(code);
displayResult(decoded);
} else {
result.innerHTML = "未在图片中识别到二维码。";
}
};
img.src = e.target.result;
};
reader.readAsDataURL(file);
}
function decodeQRData(code) {
// Use binaryData with UTF-8 decoding to properly support Chinese and other non-ASCII characters.
// jsQR's code.data may return a legacy string that drops multi-byte characters.
if (code.binaryData && code.binaryData.length) {
try {
const bytes = new Uint8Array(code.binaryData);
return new TextDecoder('utf-8').decode(bytes);
} catch (e) {
console.error('Failed to decode QR data as UTF-8:', e);
}
}
return code.data || '';
}
function displayResult(data) {
currentResult = data;
copyResultBtn.style.display = 'inline-block';
copyResultBtn.classList.remove('copied');
copyResultBtn.textContent = '复制识别结果';
let content = data;
if (isValidUrl(content)) {
content = `<a href="${escapeHtml(data)}" target="_blank">${escapeHtml(data)}</a>`;
result.innerHTML = `${content}`;
} else {
result.textContent = `${data}`;
}
}
async function copyResult() {
if (!currentResult) return;
try {
await navigator.clipboard.writeText(currentResult);
copyResultBtn.classList.add('copied');
copyResultBtn.textContent = '已复制';
setTimeout(() => {
copyResultBtn.classList.remove('copied');
copyResultBtn.textContent = '复制识别结果';
}, 1500);
} catch (err) {
console.error('Copy failed:', err);
copyResultBtn.textContent = '复制失败';
setTimeout(() => {
copyResultBtn.textContent = '复制识别结果';
}, 1500);
}
}
function isValidUrl(string) {
try {
new URL(string);
return true;
} catch (_) {
return false;
}
}
function escapeHtml(str) {
const div = document.createElement('div');
div.textContent = str;
return div.innerHTML;
}
// --- Mode toggle ---
function setMode(mode) {
currentMode = mode;
if (mode === 'image') {
imageModeBtn.classList.add('active');
webcamModeBtn.classList.remove('active');
dropArea.style.display = 'flex';
webcamContainer.classList.remove('active');
webcamBottomControls.classList.remove('active');
stopWebcam();
} else {
webcamModeBtn.classList.add('active');
imageModeBtn.classList.remove('active');
dropArea.style.display = 'none';
webcamContainer.classList.add('active');
webcamBottomControls.classList.add('active');
result.innerHTML = '';
}
}
imageModeBtn.addEventListener('click', () => setMode('image'));
webcamModeBtn.addEventListener('click', () => setMode('webcam'));
// --- Webcam functionality ---
async function checkCameras() {
try {
const devices = await navigator.mediaDevices.enumerateDevices();
const videoDevices = devices.filter(d => d.kind === 'videoinput');
hasMultipleCameras = videoDevices.length > 1;
} catch (e) {
console.log('Could not enumerate devices:', e);
}
}
async function startWebcam() {
try {
webcamStatus.textContent = '正在请求摄像头权限...';
const constraints = {
video: {
facingMode: currentFacingMode,
width: { ideal: 640 },
height: { ideal: 480 }
}
};
webcamStream = await navigator.mediaDevices.getUserMedia(constraints);
webcamVideo.srcObject = webcamStream;
videoWrapper.style.display = 'block';
webcamPlaceholder.style.display = 'none';
startCameraBtn.style.display = 'none';
stopCameraBtn.style.display = 'inline-block';
// Reset zoom
currentScale = 1;
webcamVideo.style.transform = 'scale(1)';
await checkCameras();
if (hasMultipleCameras) {
switchCameraBtn.style.display = 'inline-block';
}
webcamStatus.textContent = '摄像头已开启,正在识别二维码...';
// Start the scanning loop
startScanLoop();
} catch (error) {
console.error('Camera error:', error);
webcamStatus.textContent = `摄像头错误:${error.message}`;
}
}
function stopWebcam() {
if (scanInterval) {
clearInterval(scanInterval);
scanInterval = null;
}
if (webcamStream) {
webcamStream.getTracks().forEach(track => track.stop());
webcamStream = null;
}
webcamVideo.srcObject = null;
videoWrapper.style.display = 'none';
webcamPlaceholder.style.display = 'flex';
startCameraBtn.style.display = 'inline-block';
stopCameraBtn.style.display = 'none';
switchCameraBtn.style.display = 'none';
webcamStatus.textContent = '';
// Reset zoom
currentScale = 1;
webcamVideo.style.transform = 'scale(1)';
}
async function switchCamera() {
currentFacingMode = currentFacingMode === 'environment' ? 'user' : 'environment';
stopWebcam();
await startWebcam();
}
function scanFrame() {
const canvas = document.createElement('canvas');
canvas.width = webcamVideo.videoWidth;
canvas.height = webcamVideo.videoHeight;
if (canvas.width === 0 || canvas.height === 0) {
return;
}
const ctx = canvas.getContext('2d');
ctx.drawImage(webcamVideo, 0, 0, canvas.width, canvas.height);
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
const code = jsQR(imageData.data, imageData.width, imageData.height);
if (code) {
const decoded = decodeQRData(code);
displayResult(decoded);
webcamStatus.textContent = '已识别到二维码!继续扫描中...';
}
}
function startScanLoop() {
if (scanInterval) {
clearInterval(scanInterval);
}
// Scan once video is ready
webcamVideo.addEventListener('loadeddata', () => {
scanFrame();
}, { once: true });
// Then scan every 200ms
scanInterval = setInterval(() => {
if (webcamStream) {
scanFrame();
}
}, 200);
}
// Webcam button handlers
startCameraBtn.addEventListener('click', startWebcam);
stopCameraBtn.addEventListener('click', stopWebcam);
switchCameraBtn.addEventListener('click', switchCamera);
copyResultBtn.addEventListener('click', copyResult);
// --- Pinch-to-zoom ---
function getDistance(touches) {
const dx = touches[0].clientX - touches[1].clientX;
const dy = touches[0].clientY - touches[1].clientY;
return Math.sqrt(dx * dx + dy * dy);
}
videoWrapper.addEventListener('touchstart', (e) => {
if (e.touches.length === 2) {
e.preventDefault();
initialDistance = getDistance(e.touches);
initialScale = currentScale;
zoomHint.style.opacity = '1';
}
}, { passive: false });
videoWrapper.addEventListener('touchmove', (e) => {
if (e.touches.length === 2 && initialDistance !== null) {
e.preventDefault();
const currentDistance = getDistance(e.touches);
const scaleFactor = currentDistance / initialDistance;
currentScale = Math.min(Math.max(initialScale * scaleFactor, 1), 4);
webcamVideo.style.transform = `scale(${currentScale})`;
zoomHint.textContent = `${currentScale.toFixed(1)}x 缩放`;
}
}, { passive: false });
videoWrapper.addEventListener('touchend', (e) => {
if (e.touches.length < 2) {
initialDistance = null;
zoomHint.style.opacity = '0';
zoomHint.textContent = '双指捏合缩放';
}
});
// Double-tap to reset zoom
let lastTap = 0;
videoWrapper.addEventListener('touchend', (e) => {
if (e.touches.length === 0) {
const now = Date.now();
if (now - lastTap < 300) {
currentScale = 1;
webcamVideo.style.transform = 'scale(1)';
zoomHint.textContent = '缩放已重置';
zoomHint.style.opacity = '1';
setTimeout(() => {
zoomHint.style.opacity = '0';
zoomHint.textContent = '双指捏合缩放';
}, 500);
}
lastTap = now;
}
});
};
</script>
</body>
</html>