js
var app = getApp()
Page({
/**
* 生命周期函数--监听页面加载
*/
data: {
cardInfo: {
// avater: "https://xianganzhu.oss-cn-chengdu.aliyuncs.com/images/goods/cover/7999_1.jpg", //需要https图片路径
// qrCode: "https://xianganzhu.oss-cn-chengdu.aliyuncs.com/images/qr_code/820f2ae4-4fce-11ea-a7f3-00163e013b68.png", //需要https图片路径
TagText: "湘安", //标签
Name: '小姐姐', //姓名
Position: "程序员鼓励师", //职位
Company: "才华无限有限公司", //公司
Positiona: '123'
},
type: ''
},
onLoad: async function(options) {
console.log(options.id)
this.ersa(options.id)
this.getavals()
},
all: function() {
var that = this
that.setData({
type: 'all'
})
this.getavals();
},
getBG(url) {
// Promise函数给我很大的帮助,让我能return出回调函数中的值
return new Promise(function(resolve) {
wx.downloadFile({
url: url,
success: function(res) {
url = res.tempFilePath;
resolve(url);
}
});
});
},
getavals() {
console.log('los')
wx.showLoading({
title: '生成中...',
mask: true,
});
var that = this;
var url = that.data.sptp // 商品图片
var urlqCord = that.data.erwm // 二维码
var urlavati = that.data.userInfo.avatarurl // 头像
var aa = Promise.all([that.getBG(url), that.getBG(urlqCord), that.getBG(urlavati)]).then(res => {
console.log(123, res)
that.sharePosteCanvas(res[0], res[1], res[2])
})
},
/**
* 开始用canvas绘制分享海报
*/
sharePosteCanvas: function(avaterSrc, codeSrc, avaterSrcasd) {
wx.showLoading({
title: '生成中...',
mask: true,
})
var that = this;
var cardInfo = that.data.cardInfo; //需要绘制的数据集合
const ctx = wx.createCanvasContext('myCanvas'); //创建画布
var width = "";
wx.createSelectorQuery().select('#canvas-container').boundingClientRect(function(rect) {
var height = rect.height;
var right = rect.right;
width = rect.width * 0.8;
var left = rect.left + 5;
ctx.setFillStyle('#fff');
ctx.fillRect(0, 0, rect.width, height);
//头像为正方形
if (avaterSrc) {
ctx.drawImage(avaterSrc, left, 20, width, width);
ctx.setFontSize(14);
ctx.setFillStyle('#fff');
ctx.setTextAlign('left');
}
//标签
if (cardInfo.TagText) {
ctx.fillText(cardInfo.TagText, left + 20, width - 4);
const metrics = ctx.measureText(cardInfo.TagText); //测量文本信息
ctx.stroke();
ctx.rect(left + 10, width - 20, metrics.width + 20, 25);
ctx.setFillStyle('rgba(255,255,255,0.4)');
ctx.fill();
}
//姓名
if (cardInfo.Name) {
const CONTENT_ROW_LENGTH = 11; // 正文 单行显示字符长度
let [contentLeng, contentArray, contentRows] = that.textByteLength(cardInfo.Name, CONTENT_ROW_LENGTH);
ctx.setFontSize(14);
ctx.setFillStyle('#000');
ctx.setTextAlign('left');
ctx.fillText(cardInfo.Name, left, width + 60);
}
//职位
if (cardInfo.Position) {
ctx.setFontSize(12);
ctx.setFillStyle('#666');
ctx.setTextAlign('left');
ctx.fillText(cardInfo.Position, left, width + 85);
}
if (cardInfo.Positiona) {
ctx.setFontSize(12);
ctx.setFillStyle('#16ba63');
ctx.setTextAlign('left');
ctx.fillText(cardInfo.Positiona, left, width + 105);
}
//电话
if (cardInfo.Mobile) {
ctx.setFontSize(12);
ctx.setFillStyle('#666');
ctx.setTextAlign('left');
ctx.fillText(cardInfo.Mobile, left, width + 105);
}
// 公司名称
if (cardInfo.Company) {
const CONTENT_ROW_LENGTH = 24; // 正文 单行显示字符长度
let [contentLeng, contentArray, contentRows] = that.textByteLength(cardInfo.Company, CONTENT_ROW_LENGTH);
ctx.setTextAlign('left');
ctx.setFillStyle('#000');
ctx.setFontSize(14);
let contentHh = 22 * 1;
for (let m = 0; m < contentArray.length; m++) {
ctx.fillText(contentArray[m], left, width + 150 + contentHh * m);
}
}
// 绘制二维码
if (codeSrc) {
ctx.drawImage(codeSrc, left + 160, width + 40, width / 3, width / 3)
ctx.setFontSize(10);
ctx.setFillStyle('#000');
ctx.fillText("微信扫码或长按识别", left + 160, width + 150);
}
// 头像 安卓和苹果显示位置不一样所以注释了
// if (avaterSrcasd) {
// ctx.restore();
// ctx.beginPath();
// ctx.arc(235, 338.5, 40 / 2, 0, Math.PI * 2, false);
// console.log(45 / 2 + (windowW - -55) / 2, 45 / 2 + (windowH + 29) / 2, 40 / 2)
// ctx.clip();
// // ctx.drawImage(avaterSrcasd, left + 150, width + 40, width / 3, width / 3);
// ctx.drawImage(
// avaterSrcasd,
// left + 160, width + 40, width / 3, width / 3,
// 40,
// 40
// );
// }
}).exec()
setTimeout(function() {
ctx.draw();
wx.hideLoading();
}, 1000)
if (that.data.type == 'all') {
this.saveShareImg()
}
},
/**
* 多行文字处理,每行显示数量
* @param text 为传入的文本
* @param num 为单行显示的字节长度
*/
textByteLength(text, num) {
let strLength = 0; // text byte length
let rows = 1;
let str = 0;
let arr = [];
for (let j = 0; j < text.length; j++) {
if (text.charCodeAt(j) > 255) {
strLength += 2;
if (strLength > rows * num) {
strLength++;
arr.push(text.slice(str, j));
str = j;
rows++;
}
} else {
strLength++;
if (strLength > rows * num) {
arr.push(text.slice(str, j));
str = j;
rows++;
}
}
}
arr.push(text.slice(str, text.length));
return [strLength, arr, rows] // [处理文字的总字节长度,每行显示内容的数组,行数]
},
//点击保存到相册
saveShareImg: function() {
var that = this;
wx.showLoading({
title: '正在保存',
mask: true,
})
setTimeout(function() {
wx.canvasToTempFilePath({
canvasId: 'myCanvas',
success: function(res) {
wx.hideLoading();
var tempFilePath = res.tempFilePath;
wx.saveImageToPhotosAlbum({
filePath: tempFilePath,
success(res) {
wx.showModal({
content: '图片已保存到相册,赶紧晒一下吧~',
showCancel: false,
confirmText: '好的',
confirmColor: '#333',
success: function(res) {
if (res.confirm) {}
},
fail: function(res) {}
})
},
fail: function(res) {
wx.showToast({
title: res.errMsg,
icon: 'none',
duration: 2000
})
}
})
}
});
}, 3000);
},
})
html
<view class='poste_box' id='canvas-container'>
<canvas canvas-id="myCanvas" style="width:100%;height:900rpx;" />
</view>
<button bind:tap="getavals">点击生成海报</button>
<button bind:tap="saveShareImg">保存到相册</button>
<button bind:tap="all">生成海报并保存到相册</button>
css
page{
background-color: #EDEEF2;
}
.poste_box{
width: 85%;
margin: auto;
margin-top: 50rpx;
background-color: #fff;
border: 1rpx solid #ddd;
box-shadow:0px 0px 10px 5px #D8D7DD;
}
.savePoste{
background-color: #FF8427;
width: 90%;
margin-left: auto;
margin-right: auto;
margin-top:30rpx;
color: #fff;
}
.saveTitle{
font-size: 25rpx;
color: #666;
width: 90%;
margin-left: auto;
margin-right: auto;
margin-top: 20rpx;
text-align: center;
}