使用 qrcode.react 绘制二维码,并下载二维码


 如果是要生成svg格式的二维码,可以使用以下方法进行下载

/**

 * 将svg导出成图片

 * @param node svg节点 => document.querySelector('svg')

 * @param name 生成的图片名称

 * @param width 生成的图片宽度

 * @param height 生成的图片高度

 * @param type 生成的图片类型

 */

export const covertSVG2Image = (node, name, width, height, type = 'png') => {

      let serializer = new XMLSerializer()

      let source = '<?xml version="1.0" standalone="no"?>\r\n' + serializer.serializeToString(node)

      let image = new Image()

    image.src = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(source)

    let canvas = document.createElement('canvas')

    canvas.width = width

    canvas.height = height

    let context = canvas.getContext('2d')

    context.fillStyle = '#fff'

    context.fillRect(0, 0, 10000, 10000)

    image.onload = function () {

      context.drawImage(image, 0, 0)

      let a = document.createElement('a')

      a.download = `${name}.${type}`

      a.href = canvas.toDataURL(`image/${type}`)

      a.click()

    }

}

 

   import QRCode from 'qrcode.react';
    const [qrcode, setQrcode] = useState('' )
 //导出canvas绘制的二维码,导出格式为png const handleClickDownLoad = () => { let canvas = $('#qrCodeBox canvas')[0]; setQrcode(canvas.toDataURL('image/png')); };

 

  <div className="qr-code" id="qrCodeBox">
    <QRCode
        renderAs="svg"//渲染格式为svg,默认为canvas
        value={"http://www.baidu.com"}//需要渲染为二维码的链接地址
        size={180}//渲染出来的二维码大小
/> <div onClick={() => covertSVG2Image($('#qrCodeBox svg')[0], '111', 180, 180)}> 点击下载svg绘制的二维码 </div> <a onClick={handleClickDownLoad} download='二维码' href={qrcode}> 点击下载canvas绘制的二维码 </a> </div>

 

 

 

 参考地址:https://www.jianshu.com/p/92d5a778d964


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM