首先引入qrcode.js库,再创建div容器用于显示二维码,接着通过new qrcode()生成固定内容二维码,然后结合input输入框和按钮实现动态生成,最后可添加css样式美化显示效果。

要使用 JavaScript 实现一个简单的二维码生成器,可以借助现有的开源库 qrcode.js,它轻量、无需依赖,并且兼容性好。下面是一个完整的实现步骤和示例代码。
1. 引入 qrcode.js 库
你可以通过 CDN 直接引入 qrcode.js,无需安装额外环境:<script src="https://<a%20style=" color: text-decoration:underline title="cdn" href="https://www.php.cn/zt/19618.html" target="_blank">cdn.jsdelivr<a style="color:#f60; text-decoration:underline;" title= ".net" href="https://www.php.cn/zt/64958.html" target="_blank">.net/<a style="color:#f60; text-decoration:underline;" title= "npm" href="https://www.php.cn/zt/16096.html" target="_blank">npm/qrcode.js/lib/qrcode.min.js"></script>
2. 创建用于渲染二维码的容器
在 HTML 中添加一个 div 元素,二维码将绘制在该元素内部(使用 Canvas):
3. 使用 JavaScript 生成二维码
通过 new QRCode() 实例化并传入配置参数,即可生成二维码:
const qrcode = new QRCode("qrcode", {
text: "https://example.com",
width: 128,
height: 128,
colorDark: "#000000",
colorLight: "#ffffff",
correctLevel: QRCode.CorrectLevel.H
});
4. 动态更新二维码内容
如果需要根据用户输入实时生成二维码,可以结合 input 输入框实现:
function makeCode() {
const inputValue = document.getElementById("text").value;
if (!inputValue) return;
const qrcodeDiv = document.getElementById("qrcode");
qrcodeDiv.innerHTML = "";
new QRCode(qrcodeDiv, {
text: inputValue,
width: 128,
height: 128,
correctLevel: QRCode.CorrectLevel.H
});
}
5. 可选:添加样式美化显示效果
给二维码容器添加边框、居中等样式提升可读性:
#qrcode {
margin-top: 20px;
text-align: center;
}
#qrcode canvas {
border: 1px solid #e0e0e0;
border-radius: 4px;
}










