Vue2 qrcode+html2canvas 实现二维码的生成和保存

1.安装

npm install qrcode

npm install html2canvas

2.引用

import QRCode from 'qrcode'

import html2canvas from 'html2canvas'

效果:

1.

二维码生成: 

 下载二维码图片:

二维码的内容:

实现代码:

<template>
  <div class="main-body module-contain">
    <div>我是测试的二维码内容h5页面: http://xxxx:8080/qrcodeContain</div>
    <div class="generateQRcode-top"
         ref="qrcodeBox"
         v-show="isShowText">
      <!-- 我是测试的二维码内容 -->
      <div ref="qrcodeContainer"
           class="qr-code"></div>
      <div class="qr-txt">产品编号: xxxx</div>
    </div>
    <el-button type="primary"
               @click="generateQRCode">生成二维码</el-button>
    <el-button type="primary"
               @click="saveQRCode">保存二维码</el-button>
  </div>
</template>

<script>
import QRCode from 'qrcode'
import html2canvas from 'html2canvas'
export default {
  data () {
    return {
      isShowText: false,
      qr: 'http://xxxx:8080/qrcodeContain' // 二维码内容-网址/数字/字母 // 可以用网上的地址测试,例如:https://www.bilibili.com/guochuang/?spm_id_from=333.1007.0.0
    }
  },
  components: {
  },
  mounted () {
  },
  methods: {
    // 生成二维码
    generateQRCode () {
      this.isShowText = true
      //每次生成的时候清空内容,否则会叠加,二维码背景色透明会一目了然
      if (this.$refs.qrcodeContainer) {
        this.$refs.qrcodeContainer.innerHTML = ''
      }
      QRCode.toDataURL(this.qr, { errorCorrectionLevel: 'H' }, (err, url) => {
        if (err) console.error(err)
        // 将二维码URL设置到容器的背景图片
        this.$refs.qrcodeContainer.style.backgroundImage = `url(${url})`
      })
    },
    // 保存二维码
    async saveQRCode () {
      // 使用html2canvas将二维码容器转换为图片
      try {
        const canvas = await html2canvas(this.$refs.qrcodeBox)
        // 创建一个图片元素
        const img = new Image()
        img.src = canvas.toDataURL('image/png')
        // 创建一个链接元素
        const link = document.createElement('a')
        // 设置下载的文件名
        link.download = '二维码.png'
        // 触发点击
        link.href = img.src
        link.click()
      } catch (error) {
        console.error(error)
      }
    },
  }
}
</script>

<style lang="less" scoped>
.module-contain {
  .generateQRcode-top {
    display: flex;
    // justify-content: space-between;
    // align-items: center;
    width: 360px;
    // height: 200px;
    margin: 20px 0;
    background-color: #fff;
    border: 1px solid #eee;
    .qr-code {
      width: 180px;
      height: 180px;
      background-position: 50% 50%;
      background-repeat: no-repeat;
      background-size: contain;
      text-align: center;
      font-size: 20px;
      font-weight: bold;
    }
    .qr-txt {
      padding: 12px 0;
      font-size: 14px;
    }
  }
}
</style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值