js实现将链接生成二维码,并对生成的二维码转换为图片,右击可保存至本地

在vue项目中,实现将链接生成二维码;可识别跳转,将生成的二维码可转换成图片,并可保存至本地。具体操作步骤如下:

1.安装及引用

首先,实现这个功能需要使用QRCode和html2canvas,所以在使用之前需要安装

npm install --save html2canvas
npm install qrcodejs2 --save

在页面中引入

import QRCode from 'qrcodejs2'
import html2canvas from 'html2canvas'

2. html部分

<template>
    <div class="code-box" ref="codeBox">
        <div ref="qrcode" class="code-content"></div>
    </div>
</template>

3. js部分

3.1 二维码生成

	watch: {
	        url(val) {
	            console.log("val", val)
	            this.initCode()
	        }
	    },
    mounted() {
        this.initCode()
    },
    methods: {
        initCode() {
            // 使用$nextTick确保数据渲染
            this.$nextTick(() => {
                if (this.url) {
                    this.codeWidth = Number(this.$refs.codeBox.clientHeight)
                    this.codeHeight = Number(this.$refs.codeBox.clientWidth)
                    this.showCode(this.codeWidth, this.codeHeight)
                }
            })
        },
        showCode(width, height) {
            if (this.$refs.qrcode) {
                this.$refs.qrcode.innerHTML = ''
            }
            const qrcode = new QRCode(this.$refs.qrcode, {
                text: this.url, //要跳转的链接
                width: width || 200,
                height: height || 200, 
                colorDark: this.colorDark,
                colorLight: this.colorLight, 
                correctLevel: QRCode.CorrectLevel.L // L M  H
            })
            this.createPicture()
        },

3.2 生成图片

createPicture() {
            html2canvas(this.$refs.qrcode, {
                backgroundColor: null,
                width: 200,
                height: 200
            }).then(canvas => {
                const imgData = canvas.toDataURL('image/jpeg')
                this.imgData = imgData
            })
        }

这样就可以啦 效果图就先不放了,有帮助的话记得点赞

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值