vue实现图片和生成二维码的合成
更新:HHH   时间:2023-1-7


本文主要讲述生成二维码并合并二维码与图片的功能。

第一步:生成二维码图片
安装:yarn add qrcanvas --save
组件中引入:import { qrcanvas } from 'qrcanvas';
组件使用:

<template>
    <div>
        <div v-else>
            <img src="./poster.png">
            <div id="qrcode" class="vue_img" ref="box"></div>
        </div>
    </div>
</template>

script中代码:

let that = this;
that.appSrc = "www.baidu.com";
that.$nextTick(function () {
        //生成二维码
        var canvas1 = qrcanvas({
                data: decodeURIComponent(that.appSrc),
                size:80
        });
        document.getElementById("qrcode").innerHTML = '';
        document.getElementById('qrcode').appendChild(canvas1);
});

第二步:合成二维码和图片
安装:yarn add html2canvas --save
组件中引入:import html2canvas from 'html2canvas';
组件使用:

<template>
    <div>
        <img v-if="imgUrl" :src="imgUrl" alt="分享图片">
    </div>
</template>

script中代码:

let that = this;
that.appSrc = "www.baidu.com";
that.$nextTick(function () {
        //合成分享图
        html2canvas(that.$refs.box).then(function(canvas) {
                //错误写法,此处会触发坑二
                //that.imgUrl =  URL.createObjectURL(that.base64ToBlob(canvas.toDataURL())) 
                //正确写法
                let dataURL = canvas.toDataURL("image/png");
                that.imgUrl = dataURL;
        });
});

方法base64ToBlob:

base64ToBlob(code) {
        let parts = code.split(';base64,');
        let contentType = parts[0].split(':')[1];
        let raw = window.atob(parts[1]);
        let rawLength = raw.length;

        let uInt8Array = new Uint8Array(rawLength);

        for (let i = 0; i < rawLength; ++i) {
                uInt8Array[i] = raw.charCodeAt(i);
        }
        return new Blob([uInt8Array], {type: contentType});
}
坑一:使用canvas生成二维码以便之后实现合成
坑二:生成的图片需要转化为base64格式才能保存

完整代码呈现:

<template>
    <div class="productShare">
        <img v-if="imgUrl" :src="imgUrl" alt="分享图片">
        <div v-else  ref="box">
            <img :src=""./poster.png"">
            <div id="qrcode"></div>
        </div>
    </div>
</template>

script中代码:

let that = this;   
that.appSrc = "www.baicu.com";
that.$nextTick(function () {
        //生成二维码
        var canvas1 = qrcanvas({
                data: decodeURIComponent(that.appSrc),
                size:80
        });
        document.getElementById("qrcode").innerHTML = '';
        document.getElementById('qrcode').appendChild(canvas1);

        //合成分享图
        html2canvas(that.$refs.box).then(function(canvas) {
                let dataURL = canvas.toDataURL("image/png");
                that.imgUrl = dataURL;
        });
});
返回web开发教程...