直接上所有代码了
<view class="phonemain">
<canvas canvas-id="shareImg" style="width:750px;height:1320px;" ></canvas>
<!-- 预览区域 -->
<view hidden='{{hidden}}' class='preview' height="{{wxheight}}rpx">
<image src='{{prurl}}' mode='widthFix'></image>
<button size='mini' bindtap='save' wx:if="{{ saveImgBtnHidden}}">保存至相册</button>
<button size='mini' class='openSetting' open-type="openSetting"
bindopensetting='handleSetting' wx:if="{{openSettingBtnHidden}}" >去授权</button>
</view>
</view>
res是后台返回的图片和文字信息,
if (res.result == 1 && res.value) {
// console.log(res);
let resimg = res.value;
let qrcode = resimg.tripQrCodeImgBase64;
let img1 = resimg.mxpBgBmxpBgBase4;
let img2 = resimg.headImg;
// let img1 = resimg.headImg.replace('↵', '').replace(/[\r\n]/g, "");
// let img2 = resimg.mxpBgBmxpBgBase4.replace('↵', '').replace(/[\r\n]/g, "");
// img1 = this.getBase64ImageUrl(img1);// base64编码的图片
// img2 = this.getBase64ImageUrl(img2);// base64编码的图片
let nickName = resimg.nickName;
if (nickName.length>8){//微信昵称最多可输入16个字符,本页面根据设计图,估计一行可显示6,7,个
nickName = nickName.slice(0,8)+'...'
};
let words = resimg.words;//内容
let wordsnew = '';
if (resimg.words.length && resimg.words.length>0){
let wordslength = resimg.words.length - 1;//内容数组
var rl = Math.floor(Math.random() * wordslength); // 随机获取内容数组的某一条
wordsnew = words[rl];
}
if (wordsnew.length > 20) {
wordsnew = wordsnew.slice(0, 20)
};
// let img1 = 'http://travel.enn.cn/group1/M00/00/44/CiaAUl1BjFeAW_C7ABg89jtJHpg057.png';
// let img2 = 'https://ss1.bdstatic.com/6OF1bjeh1BF3odCf/it/u=829888290,2650878176&fm=74&app=80&f=JPG&size=f121,121?sec=1880279984&t=274501980523d63a7d93c94f85aabbab';
wx.showLoading({
title: '图片生成中...'
})
that.setData({
imgUrl: qrcode
});
var promise1="";
if (img1 && img1!='' ){
promise1 = that.downfile(img1);
}
var promise2 = that.downfile(img2);
var promise3 = that.downfile(that.data.imgUrl);
Promise.all([
promise1, promise2, promise3
]).then(res => {
var ctx = wx.createCanvasContext('shareImg')
ctx.setFillStyle('#FFFFFF')
// ctx.fillRect(0, 0, 750, 1334)
// 商品图片
ctx.drawImage(res["0"], 0, 0, 750, 1334)
// 下面是先定位要开个圆形的位置,50 和 90 分别就是圆的圆心的 x 坐标和 y 坐标,25 是半径,后面的两个参数就是起始和结束,这样就能画好一个圆了
ctx.save();
ctx.beginPath();
ctx.arc(110, 1212, 65, 0, 2 * Math.PI);
// 从画布上裁剪出这个圆形
ctx.closePath();
ctx.clip();
// this.circleImg(ctx,res["1"], 45, 1147, 65);
ctx.drawImage(res["1"], 45, 1147, 130, 130);
ctx.restore(); // 还原状态
// 商品名称
ctx.font = "32rpx PingFangSC-Semibold,PingFang SC"
ctx.setFillStyle("#4A4A4A")
that.textHandle(ctx, nickName, 221, 1181, 290, 45);
// 商品介绍
ctx.font = "24rpx PingFangSC-Semibold,PingFang SC"
ctx.setFillStyle("#4A4A4A")
that.textHandle(ctx, wordsnew, 221, 1236, 290, 33);
// 二维码图片
ctx.drawImage(res["2"], 575, 1147, 130, 130);
ctx.draw(true)
return res;
}).then(res => {
console.log(res);
// if (res.length == 2) {
setTimeout(function() {
that.share();
}, 2000);
// }
});
}
下面是引用的一些方法:
downfile(url) {
return new Promise(function(resolve, reject) {
wx.downloadFile({
url: url,
success: function(res) {
console.log(res);
resolve(res.tempFilePath)
},
fail(res) {
},
complete(res) {
console.log(res);
},
})
})
},
savaImageToPhoto: function() {
var that = this
wx.canvasToTempFilePath({
x: 0,
y: 0,
width: 750,
height: 1334,
destWidth: 640, //320 640
destHeight: 1138, //537 1074
canvasId: 'shareImg',
quality: 1,
success: function(res) {
console.log(res.tempFilePath);
that.setData({
prurl: res.tempFilePath,
})
wx.hideLoading()
},
fail: function(res) {
console.log(res)
}
});
},
share: function() {
var that = this
that.savaImageToPhoto();
wx.getSetting({
success(res) {
console.log(res);
if (!res.authSetting['scope.writePhotosAlbum']) {
//没有获取授权
wx.authorize({
scope: 'scope.writePhotosAlbum',
success(res) { //这里是用户同意授权后的回调
console.log(res);
that.setData({
saveImgBtnHidden: true,
openSettingBtnHidden: false,
});
},
fail(res) { 这里是用户拒绝授权后的回调
that.setData({
saveImgBtnHidden: false,
openSettingBtnHidden: true,
})
}
})
} else { //有授权的功能
//获取授权后的
that.setData({
saveImgBtnHidden: true,
openSettingBtnHidden: false,
});
// that.savaImageToPhoto();
}
}
})
},
/**
* 保存到相册
*/
save: function() {
let openId = wx.getStorageSync("userInfo")
if (!openId) {
wx.navigateTo({
url: impowerlogin,
})
} else {
var that = this
//生产环境时 记得这里要加入获取相册授权的代码
wx.saveImageToPhotosAlbum({
filePath: that.data.prurl,
success(res) {
console.log(res)
wx.showToast({
title: '图片保存到相册',
mask: false,
icon: 'success',
success: function () {
}
})
},
fail(err) {
console.log(err)
}
})
}
},
handleSetting: function(e) {
let that = this;
// 对用户的设置进行判断,如果没有授权,即使用户返回到保存页面,显示的也是“去授权”按钮;同意授权之后才显示保存按钮
if (!e.detail.authSetting['scope.writePhotosAlbum']) {
wx.showModal({
title: '警告',
content: '若不打开授权,则无法将图片保存在相册中!',
showCancel: false
})
that.setData({
saveImgBtnHidden: false,
openSettingBtnHidden: true
})
} else {
wx.showModal({
title: '提示',
content: '您已授权,赶紧将图片保存在相册中吧!',
showCancel: false
})
that.setData({
saveImgBtnHidden: true,
openSettingBtnHidden: false
})
}
},
//文字换行
textHandle(ctx, text, numX, numY, textWidth, lineHeight) {
var chr = text.split(""); // 将一个字符串分割成字符串数组
var temp = "";
var row = [];
for (var a = 0; a < chr.length; a++) {
if (ctx.measureText(temp).width < textWidth) {
temp += chr[a];
} else {
a--; // 添加a--,防止字符丢失
row.push(temp);
temp = "";
}
}
row.push(temp);
// 如果数组长度大于2 则截取前两个
if (row.length > 2) {
var rowCut = row.slice(0, 2);
var rowPart = rowCut[1];
var test = "";
var empty = [];
for (var a = 0; a < rowPart.length; a++) {
if (ctx.measureText(test).width < textWidth - 10) {
test += rowPart[a];
} else {
break;
}
}
empty.push(test);
var group = empty[0] + "..."; // 这里只显示两行,超出的用...展示
rowCut.splice(1, 1, group);
row = rowCut;
}
for (var b = 0; b < row.length; b++) {
ctx.fillText(row[b], numX, numY + b * lineHeight);
}
},
//base64转换成图片
getBase64ImageUrl: function (data) {
/// 获取到base64Data
var base64Data = data;
/// 通过微信小程序自带方法将base64转为二进制去除特殊符号,再转回base64
base64Data = wx.arrayBufferToBase64(wx.base64ToArrayBuffer(base64Data));
/// 拼接请求头,data格式可以为image/png或者image/jpeg等,看需求
// const base64ImgUrl = "data:image/png;base64," + base64Data;
const base64ImgUrl = base64Data;
/// 刷新数据
return base64ImgUrl;
},