效果图如上
1.安装依赖 npm install qrcode (生成二维码) html2canvas (截取html元素生成图片) 2.结构
<div id="posterHtml" :style="{backgroundImage: 'url('+posterHtmlBg+')'}" v-show="false">
<div class="cnnvasName">
<canvas id="canvas" width="750" height="220"></canvas>
</div>
<div class="cnnvasName">
<canvas id="canvasTitle" width="750" height="200"></canvas>
</div>
<div id="poster">
<canvas id="qrcodeImg" ref="qrcodeImg" width="200" height="200"></canvas>
</div>
</div>
3.先生成二维码
generateQRCode(content) {
this.showQrcode = true;
this.$nextTick(() => {
const canvas = this.$refs.qrcodeImg
canvas.width = 200;
canvas.height = 200;
canvas.getContext("2d").clearRect(0, 0, canvas.width, canvas.height);
qrcode.toCanvas(
canvas,
content,
{
width: 200,
},
(error) => {
this.createPoster()
}
);
});
},
4.生成并下载海报的方法
createPoster() {
const domObj = document.getElementById('posterHtml')
html2canvas(domObj, {
useCORS: true,
allowTaint: false,
logging: false,
letterRendering: true,
onclone(doc) {
let e = doc.querySelector('#posterHtml')
e.style.display = 'block'
}
}).then(function(canvas) {
var a = document.createElement("a");
a.href = canvas.toDataURL();
a.download = "drcQrcodePoster";
a.click();
})
},
附: 主标题和副标题用canvas生成的代码
var canvas=document.getElementById('canvas');
var ctx=canvas.getContext("2d");
var canvas=document.getElementById('canvasTitle');
var ctxTitle=canvas.getContext("2d");
ctx.textBaseline = 'top';
ctx.fillStyle="#ffffff";
ctx.shadowColor = 'rgba(250, 166, 120, 1)';
ctx.shadowOffsetX = 3;
ctx.shadowOffsetY = 5;
ctx.shadowBlur = 2;
ctx.font = "bold 90px SimHei";
ctx.textAlign='center'
ctx.fillText(data,375,110);
ctxTitle.font = "bold 33px SimHei";
ctxTitle.fillStyle="#ffffff";
ctxTitle.textAlign='center'
ctxTitle.fillText('欢迎您把'+data+'介绍给您的朋友',375,60);
我这里之所以用canvas生成标题,是因为用div插值的方式(如下),生成的图片竟然没有文字,不得已才用canvas的
<div class="cnnvasName">欢迎您把{{data}}介绍给您的朋友 </div>
|