废话不多说直接上代码,简洁明了,看不懂可以问我的哈
.wxml文件
<view class='saveBtn f16' bindtap='showCanvasimage'>保存到手机</view>
<view class="back" hidden='{{back}}' >
<Canvas canvasId='cpimg' disable-scroll='true' style='width:375PX;height:580PX'></Canvas>
</view>
.wxss文件
.back{
width: 100%;
background: rgba(0, 0, 0, 0.3);
position: absolute;
top:0;
bottom:0;
left:0;
right:0;
z-index: 10;
}
.js文件
var canvas;
Page({
data:{
userinfo: '',
code:'',
back:true, //二维码遮罩层
headimg:'',//头像
background:'',//背景图片
qrcode: "",//二维码
exportPicH: '',
exportPicW: '',
},
onLoad:function(options){
var canvasId = "cpimg";
canvas = wx.createCanvasContext(canvasId);
//请求后台接口得到二维码code和用户信息userinfo
},
showCanvasimage() {
var that = this;
that.setData({
back: false,
})
wx.downloadFile({
url: that.data.userinfo.background, //背景图片
success: function (res) {
if (res.statusCode === 200) {
that.setData({
background: res.tempFilePath
});
wx.downloadFile({
url:that.data.code, //二维码
success: function (res) {
if (res.statusCode === 200) {
that.setData({
qrcode: res.tempFilePath
});
wx.downloadFile({
url: that.data.userinfo.headimg, //头像
success: function (res) {
if (res.statusCode === 200) {
that.setData({
headimg: res.tempFilePath
});
that.drawImage();
}
}
})
}
}
})
}
}
})
},
drawImage() {
var that = this;
let mobileWidth = 0;
let mobileHeight = 0;
wx.getSystemInfo({
success: function (res) {
mobileWidth = res.windowWidth;
mobileHeight = res.windowHeight;
},
});
this.setDate({
exportPicH: mobileHeight,
exportPicW: mobileWidth,
});
canvas.save();
canvas.drawImage(that.data.background, 0, 0, 375, 580);
//创建一个圆形
canvas.arc(mobileWidth / 2, 60, 40, 0, Math.PI * 2);
canvas.setFillStyle('#fff');
canvas.fill();
canvas.clip();
canvas.drawImage(that.data.userinfo.avatar, 147, 20, 80, 80);
canvas.restore();
canvas.drawImage(that.data.qrcode, 136, 167, 95, 80);
//文字居中显示
canvas.setFontSize(16);
canvas.setFillStyle('#fff');
canvas.setTextAlign('center');
canvas.fillText(that.data.userinfo.nickname, mobileWidth / 2,120);
canvas.draw(this.savePic);
setTimeout(function () {
that.savePic();//一开始写的this.savePic()保存下来的图片是空白的
}, 1000)
},
savePic() {
let that = this;
wx.canvasToTempFilePath({
x: 0,
y: 0,
width: that.data.exportPicW,
height: that.data.exportPicH,
canvasId: 'cpimg',
fileType: "jpg",
quality:1,
success: function (res) {
//保存到相册
wx.saveImageToPhotosAlbum({
filePath: res.tempFilePath,
success(res1) {
wx.showToast({
title: '保存成功,请打开微信朋友圈上传',
icon: 'none',
})
}
})
}
})
}
})