Skip to content

Instantly share code, notes, and snippets.

@flipeador
Last active November 21, 2024 09:02
Show Gist options
  • Save flipeador/15e98b2a774affeffd5109f14a8d588a to your computer and use it in GitHub Desktop.
Save flipeador/15e98b2a774affeffd5109f14a8d588a to your computer and use it in GitHub Desktop.
QR code generator example.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>QR Code Generator</title>
<style>
html {
display: grid;
place-content: center;
color-scheme: light dark;
}
body {
display: grid;
gap: 1em;
}
svg, img, canvas {
display: none;
}
svg {
aspect-ratio: 1;
shape-rendering: crispEdges;
}
img {
image-rendering: pixelated;
}
</style>
<script type="importmap">
{
"imports": {
"qrcode": "https://cdn.jsdelivr.net/gh/flipeador/secure-password-generator/extension/lib/qrcode.js"
}
}
</script>
</head>
<body>
<h1>QR Code Generator</h1>
<svg></svg>
<img></img>
<canvas></canvas>
<label>
Text:
<input/>
</label>
<label>
Error correction level:
<select>
<option value="L" selected>Low (7%)</option>
<option value="M">Medium (15%)</option>
<option value="Q">Quartile (25%)</option>
<option value="H">High (30%)</option>
</select>
</label>
<label>
Element type:
<select>
<option value="svg" selected>SVG</option>
<option value="img">IMG</option>
<option value="canvas">Canvas</option>
</select>
</label>
<label>
Size:
<input type="number"/>
</label>
<script type="module">
import * as QRC from 'qrcode';
const $svg = document.querySelector('svg');
const $img = document.querySelector('img');
const $canvas = document.querySelector('canvas');
const $$input = document.querySelectorAll('input');
const $$select = document.querySelectorAll('select');
$$input[1].value = QRC.CELL_SIZE_PX; // 12
function update() {
const size = parseInt($$input[1].value);
const $target = document.querySelector($$select[1].value);
for (const $element of [$svg, $img, $canvas])
$element.style.display = 'none';
$target.style.display = 'block';
const count = QRC.draw(
$target === $img ? $canvas : $target, $$input[0].value,
{ size, level: $$select[0].value, border: 'white' }
) + 2; // 2 = border
if ($target === $svg)
$svg.style.width = `${size * count}px`;
else if ($target === $img)
$img.src = $canvas.toDataURL();
}
for (const $element of [...$$input, ...$$select])
$element.addEventListener('input', () => {
clearTimeout(update.timer);
update.timer = setTimeout(() => {
document.startViewTransition ?
document.startViewTransition(update) :
update();
}, 500);
});
update();
</script>
</body>
</html>
@flipeador
Copy link
Author

flipeador commented Sep 20, 2024

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment