微信小程序生成用户带自己二维码的海报
效果图
- wxml
<canvas class="canvas-poster" id="canvasPoster" canvas-id="canvasPoster"></canvas>
<image src="{
{poster}}" style="width: 500rpx; height: 889rpx;"></image>
- 下载海报背景图片
downloadBGImg: function (phoneNumber) {
var that = this;
wx.downloadFile({
//服务器图片地址
url: "你服务器IP/bj.png",
success: function (res) {
console.log(res);
var rr = res.tempFilePath;
that.shareInfo.bgImg = rr;
//下载中间的二维码
that.downloadInviteImg(phoneNumber,true);
}
})
},
- 下载用户二维码图片
downloadInviteImg: function (phoneNumber,flag) {
var that = this;
wx.downloadFile({
//用户二维码图片,我是用每个用户的电话号码分类图片
url:phoneNumber + ".png",
success: function (res) {
console.log(res);
if (res.statusCode == 200) {
var rr = res.tempFilePath;
that.shareInfo.qrcode = rr;
var query = wx.createSelectorQuery()
query.select('#canvasPoster').boundingClientRect((res) => {
//绘制海报
that.drawImage(res)
}).exec();
} else {
if(flag==true){
//用户二维码图片是从腾讯服务器那边下载然后存到本地的服务器,所以用户第一次请求二维码图
//片时,本地服务器是没有的,调用此方法将二维码图片下载到本地服务器
that.getQrcode(phoneNumber);
}
}
}
})
},
- 绘制海报
drawImage(canvasAttrs) {
var that = this;
wx.getSystemInfo({
success(res) {
// 通过像素比计算出画布的实际大小(330x490)是展示的出来的大小
that.systemInfo = res
}
})
let ctx = wx.createCanvasContext('canvasPoster', this)
let canvasW = canvasAttrs.width // 画布的真实宽度
let canvasH = canvasAttrs.height //画布的真实高度
let headerW = 48 * this.systemInfo.pixelRatio
let qrcodeW = 300
let qrcodeX = (canvasW - qrcodeW)/2 //定位到中间
let qrcodeY = canvasH/14*8
// 填充背景
ctx.drawImage(this.shareInfo.bgImg, 0, 0, canvasW, canvasH)
ctx.save()
ctx.drawImage(this.shareInfo.qrcode, qrcodeX, qrcodeY, qrcodeW, qrcodeW)
ctx.save()
//绘制邀请文字 此处的邀请码是显示在二维码下方的,用户二维码本身是带有同样邀请码的(服务器完成)
let msg="邀请码 : "+this.data.myInviteCode;
//计算文本长度
ctx.setFontSize(30);
let msgLength=ctx.measureText(msg).width;
let textWidth= (canvasW - msgLength)/2 ;
let textHeight = canvasH/15*13
//绘制文字背景 =>圆角矩形
this.roundRect(ctx,textWidth-20, textHeight-42.5, msgLength+35, 60,35,'#dd555a');
ctx.setFillStyle('#ffffff');
//绘制文字
ctx.fillText(msg, textWidth, textHeight)
ctx.draw()
setTimeout(() => {
wx.canvasToTempFilePath({
canvasId: 'canvasPoster',
x: 13,
y: 13,
width: canvasW - 26,
height: canvasH - 26,
destWidth: canvasW - 26,
destHeight: canvasH - 26,
success: (res) => {
that.setData({
poster: res.tempFilePath,
showBoxView: true
})
wx.hideLoading();
}
})
}, 200)
},
roundRect(ctx, x, y, w, h, r, c = '#fff') {
if (w < 2 * r) { r = w / 2; }
if (h < 2 * r) { r = h / 2; }
ctx.beginPath();
ctx.fillStyle = c;
ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5);
ctx.moveTo(x + r, y);
ctx.lineTo(x + w - r, y);
ctx.lineTo(x + w, y + r);
ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2);
ctx.lineTo(x + w, y + h - r);
ctx.lineTo(x + w - r, y + h);
ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5);
ctx.lineTo(x + r, y + h);
ctx.lineTo(x, y + h - r);
ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI);
ctx.lineTo(x, y + r);
ctx.lineTo(x + r, y);
ctx.fill();
ctx.closePath();
},