You need to enable JavaScript to run this app. 使用Nayuki QR Code Generator Library生成二维码出错该如何排查?
优惠活动
大模型
产品
解决方案
定价
更多

使用Nayuki QR Code Generator Library生成二维码出错该如何排查?

问题排查与修复方案

现有代码的问题

  • 未引入QR码生成库的核心JS依赖,仅复制了页面DOM结构,没有生成二维码的核心能力
  • 缺少触发二维码生成的业务逻辑,没有实现「读取输入框内容→调用库生成QR数据→渲染到canvas/svg」的执行流程
  • 代码中冗余的xmlns属性属于XHTML规范残留,普通HTML页面不需要额外声明,可以删除

可运行的完整实现步骤

  1. 先将你找到的QR码生成库的JS文件下载到你的项目目录,命名为qrcodegen.js
  2. 使用以下完整代码替换你的原有代码:
<!DOCTYPE html>
<html>
<head>
    <!-- 引入本地的QR码生成库JS -->
    <script src="./qrcodegen.js"></script>
</head>
<body>
    <textarea placeholder="输入要生成二维码的内容" id="text-input" style="width:100%; max-width:30em; height:5em; font-family:inherit"></textarea>
    <br>
    <canvas id="qrcode-canvas" width="232" height="232"></canvas>

    <script>
        const textInput = document.getElementById('text-input');
        const canvas = document.getElementById('qrcode-canvas');
        const ctx = canvas.getContext('2d');

        // 监听输入框内容变化,实时生成二维码
        textInput.addEventListener('input', updateQrCode);

        function updateQrCode() {
            const text = textInput.value.trim();
            if (!text) {
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                return;
            }
            // 调用QR库生成二维码
            const qr = qrcodegen.QrCode.encodeText(text, qrcodegen.QrCode.Ecc.MEDIUM);
            const scale = 8; // 每个二维码点的像素大小
            const border = 4; // 白边大小
            const size = qr.size * scale + border * 2 * scale;
            canvas.width = canvas.height = size;
            ctx.fillStyle = '#ffffff';
            ctx.fillRect(0, 0, size, size);
            ctx.fillStyle = '#000000';
            for (let y = 0; y < qr.size; y++) {
                for (let x = 0; x < qr.size; x++) {
                    if (qr.getModule(x, y)) {
                        ctx.fillRect(
                            border * scale + x * scale,
                            border * scale + y * scale,
                            scale, scale
                        );
                    }
                }
            }
        }
    </script>
</body>
</html>

多输入框内容拼接实现

如果你需要读取多个输入框的内容合并生成二维码,只需要修改updateQrCode函数中读取内容的部分,把多个输入框的 value 按照你需要的格式拼接即可,示例:

function updateQrCode() {
    // 假设你有id为input1、input2、input3的三个输入框
    const val1 = document.getElementById('input1').value.trim();
    const val2 = document.getElementById('input2').value.trim();
    const val3 = document.getElementById('input3').value.trim();
    const text = `${val1}|${val2}|${val3}`; // 用竖线分隔多个内容,可自定义分隔符
    // 后续生成逻辑和上面一致
}

内容的提问来源于stack exchange,提问作者ravendward

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.10 21:12:01