Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
197 lines (169 loc) · 6.06 KB
/
Copy pathscript.js
File metadata and controls
197 lines (169 loc) · 6.06 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
/**
* JavaScript QR Code Scanner
* ---------------------------
* Scans QR codes from the device camera or an uploaded image using the
* lightweight jsQR library. No backend, no frameworks — just vanilla JS.
*/
// ----- DOM references -------------------------------------------------------
const video = document.getElementById("video");
const canvas = document.getElementById("canvas");
const placeholder = document.getElementById("placeholder");
const startBtn = document.getElementById("startBtn");
const stopBtn = document.getElementById("stopBtn");
const fileInput = document.getElementById("fileInput");
const resultBox = document.getElementById("resultBox");
const resultText = document.getElementById("resultText");
const copyBtn = document.getElementById("copyBtn");
const scanAgainBtn = document.getElementById("scanAgainBtn");
const statusEl = document.getElementById("status");
const scannerEl = document.querySelector(".scanner");
const controlsEl = document.querySelector(".controls");
// 2D context used to grab pixels from the video/image for decoding.
const ctx = canvas.getContext("2d", { willReadFrequently: true });
// Holds the active camera stream so we can stop it later.
let stream = null;
// requestAnimationFrame id for the scanning loop.
let scanLoopId = null;
// ----- Helpers --------------------------------------------------------------
/** Show a status message, optionally styled as an error or success. */
function setStatus(message, type = "") {
statusEl.textContent = message;
statusEl.className = "status" + (type ? ` status--${type}` : "");
}
/** Display a decoded result, stop scanning, and hide the scanner UI. */
function showResult(text) {
resultText.textContent = text;
resultBox.hidden = false;
setStatus("QR code detected!", "success");
stopCamera();
scannerEl.hidden = true;
controlsEl.hidden = true;
}
/**
* Try to decode a QR code from the pixels currently drawn on the canvas.
* Returns the decoded string, or null if nothing was found.
*/
function decodeFromCanvas() {
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
const code = jsQR(imageData.data, imageData.width, imageData.height, {
inversionAttempts: "dontInvert",
});
return code ? code.data : null;
}
// ----- Camera scanning ------------------------------------------------------
/** Request camera access and begin the scanning loop. */
async function startCamera() {
// Camera APIs require a secure context (https:// or localhost).
if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
setStatus("Camera not supported in this browser.", "error");
return;
}
try {
resultBox.hidden = true;
setStatus("Requesting camera access…");
stream = await navigator.mediaDevices.getUserMedia({
video: { facingMode: "environment" }, // prefer the rear camera on phones
});
video.srcObject = stream;
await video.play();
// Toggle UI into "scanning" mode.
video.hidden = false;
placeholder.hidden = true;
startBtn.hidden = true;
stopBtn.hidden = false;
setStatus("Point your camera at a QR code…");
scanLoopId = requestAnimationFrame(tick);
} catch (err) {
setStatus("Unable to access the camera. Please grant permission.", "error");
console.error(err);
}
}
/** Per-frame scan: draw the current video frame and try to decode it. */
function tick() {
if (video.readyState === video.HAVE_ENOUGH_DATA) {
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
const data = decodeFromCanvas();
if (data) {
showResult(data);
return; // stop the loop once we have a result
}
}
scanLoopId = requestAnimationFrame(tick);
}
/** Stop the camera stream and reset the preview UI. */
function stopCamera() {
if (scanLoopId) {
cancelAnimationFrame(scanLoopId);
scanLoopId = null;
}
if (stream) {
stream.getTracks().forEach((track) => track.stop());
stream = null;
}
video.hidden = true;
placeholder.hidden = false;
startBtn.hidden = false;
stopBtn.hidden = true;
}
// ----- Image upload scanning ------------------------------------------------
/** Decode a QR code from an uploaded image file. */
function handleFile(file) {
if (!file) return;
stopCamera();
resultBox.hidden = true;
setStatus("Reading image…");
const reader = new FileReader();
reader.onload = (e) => {
const img = new Image();
img.onload = () => {
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0);
const data = decodeFromCanvas();
if (data) {
showResult(data);
} else {
setStatus("No QR code found in that image.", "error");
}
};
img.onerror = () => setStatus("Could not load that image.", "error");
img.src = e.target.result;
};
reader.onerror = () => setStatus("Could not read that file.", "error");
reader.readAsDataURL(file);
}
// ----- Result actions -------------------------------------------------------
/** Copy the decoded result to the clipboard. */
async function copyResult() {
const text = resultText.textContent;
if (!text) return;
try {
await navigator.clipboard.writeText(text);
setStatus("Result copied to clipboard!", "success");
} catch {
setStatus("Could not copy to clipboard.", "error");
}
}
/** Reset the UI so the user can scan another code. */
function scanAgain() {
resultBox.hidden = true;
resultText.textContent = "";
fileInput.value = "";
scannerEl.hidden = false;
controlsEl.hidden = false;
setStatus("");
startCamera();
}
// ----- Event listeners ------------------------------------------------------
startBtn.addEventListener("click", startCamera);
stopBtn.addEventListener("click", () => {
stopCamera();
setStatus("Camera stopped.");
});
fileInput.addEventListener("change", (e) => handleFile(e.target.files[0]));
copyBtn.addEventListener("click", copyResult);
scanAgainBtn.addEventListener("click", scanAgain);
// Stop the camera cleanly when leaving the page.
window.addEventListener("beforeunload", stopCamera);