Skip to content

Instantly share code, notes, and snippets.

@flipeador
Created September 20, 2024 13:42
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.
<!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 {
aspect-ratio: 1;
shape-rendering: crispEdges;
}
img {
image-rendering: pixelated;
}
svg, img, canvas {
border: 16px solid white;
}
</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" value="12"/>
</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');
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 }
);
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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment