qrcode 如何生成底部带文字二维码

46 阅读1分钟

1、下载npm包

    yarn add qrcode
    yarn add @types/qrcode

2、React 组件

    import QRCode from "qrcode";

    const QRCodeBox = ({ value, width = 190, color = '#000', light = '#fff', qrSize = 180, qrText = '', qrTextSize = 14, }) =>{
    
    const qrCodeOption: any = {
        errorCorrectionLevel: "H",
        width: width,
        version: 7,
        margin: 6,
        color: {
          dark: color,
          light: light
        }
    };
    const handleQRcode = () => {
        let dom = document.getElementById('canvas')
        if (dom) {
          QRCode.toDataURL(value, qrCodeOption).then((url: string) => {

            const ctx = dom.getContext("2d") as CanvasRenderingContext2D;
            const image = new Image();
            image.src = url;
            new Promise<HTMLImageElement>((resolve) => {
              image.onload = () => {
                resolve(image);
              };
            }).then((img: HTMLImageElement) => {

              ctx.drawImage(img, (width - qrSize) / 2, 0, qrSize, qrSize);

              if (qrText) {
                //设置字体
                ctx.font = "bold " + qrTextSize + "px Arial";
                let tw = ctx.measureText(qrText).width; // 文字真实宽度
                let ftop = qrSize - qrTextSize; // 根据字体大小计算文字top
                let fleft = (width - tw) / 2; // 根据字体大小计算文字left
                ctx.textBaseline = "top"; //设置绘制文本时的文本基线。
                ctx.fillStyle = "#333";
                ctx.fillText(qrText, fleft, ftop);
              }
              console.log(dom.toDataURL("image/png", 1))
            })


          }).catch((err: Error) => {
            console.error(err);
          });
        }

      }


       useEffect(() => {
        if (value) handleQRcode()
      }, [value])
    
        return (
            <canvas id="canvas" className='canvas' width={width} height={width} />
        )
    }

3、qrcode 文档地址

github.com/soldair/nod…