您好,登錄后才能下訂單哦!
本文主要講述生成二維碼并合并二維碼與圖片的功能。
第一步:生成二維碼圖片
安裝: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) {
//錯誤寫法,此處會觸發(fā)坑二
//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生成二維碼以便之后實現(xiàn)合成
坑二:生成的圖片需要轉(zhuǎn)化為base64格式才能保存
完整代碼呈現(xiàn):
<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;
});
});
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。