-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
88 lines (79 loc) · 2.09 KB
/
index.js
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
const download = document.querySelector(".download");
const dark = document.querySelector(".dark");
const light = document.querySelector(".light");
const qrContainer = document.querySelector("#qr-code");
const qrText = document.querySelector(".qr-text");
const shareBtn = document.querySelector(".share-btn");
const sizes = document.querySelector(".sizes");
dark.addEventListener("input", handleDarkColor);
light.addEventListener("input", handleLightColor);
qrText.addEventListener("input", handleQRText);
sizes.addEventListener("change", handleSize);
shareBtn.addEventListener("click", handleShare);
const defaultUrl = "https://youtube.com/@AsmrProg";
let colorLight = "#fff",
colorDark = "#000",
text = defaultUrl,
size = 300;
function handleDarkColor(e) {
colorDark = e.target.value;
generateQRCode();
}
function handleLightColor(e) {
colorLight = e.target.value;
generateQRCode();
}
function handleQRText(e) {
const value = e.target.value;
text = value;
if (!value) {
text = defaultUrl;
}
generateQRCode();
}
async function generateQRCode() {
qrContainer.innerHTML = "";
new QRCode("qr-code", {
text,
height: size,
width: size,
colorLight,
colorDark,
});
download.href = await resolveDataUrl();
}
async function handleShare() {
setTimeout(async () => {
try {
const base64url = await resolveDataUrl();
const blob = await (await fetch(base64url)).blob();
const file = new File([blob], "QRCode.png", {
type: blob.type,
});
await navigator.share({
files: [file],
title: text,
});
} catch (error) {
alert("Your browser doesn't support sharing.");
}
}, 100);
}
function handleSize(e) {
size = e.target.value;
generateQRCode();
}
function resolveDataUrl() {
return new Promise((resolve, reject) => {
setTimeout(() => {
const img = document.querySelector("#qr-code img");
if (img.currentSrc) {
resolve(img.currentSrc);
return;
}
const canvas = document.querySelector("canvas");
resolve(canvas.toDataURL());
}, 50);
});
}
generateQRCode();