/* array arr2 海报素材 arr[0]海报背景图,arr[1]商品图,arr[2]二维码
* @param string store_name 素材文字
* @param string price 价格
* @param function successFn 回调函数
*/
function PosterCanvas(arr2, store_name, price, successFn, errFun) {
let that = this;
const ctx = uni.createCanvasContext('myCanvas');
ctx.clearRect(0, 0, 0, 0);
uni.getImageInfo({
src: arr2[0],
success: function(res) {
const WIDTH = res.width;
const HEIGHT = res.height;
ctx.drawImage(arr2[0], 0, 0, WIDTH, HEIGHT);
ctx.drawImage(arr2[1], 0, 0, WIDTH, WIDTH);
ctx.save();
let r = 90;
let d = r * 2;
let cx = 40;
let cy = 990;
ctx.drawImage(arr2[2], cx, cy, d, d);
ctx.restore();
const CONTENT_ROW_LENGTH = 40;
let [contentLeng, contentArray, contentRows] = that.textByteLength(store_name, CONTENT_ROW_LENGTH);
if (contentRows > 2) {
contentRows = 2;
let textArray = contentArray.slice(0, 2);
textArray[textArray.length - 1] += '……';
contentArray = textArray;
}
ctx.setTextAlign('center');
ctx.setFontSize(32);
let contentHh = 32 * 1.3;
for (let m = 0; m < contentArray.length; m++) {
ctx.fillText(contentArray[m], WIDTH / 2, 820 + contentHh * m);
}
ctx.setTextAlign('center')
ctx.setFontSize(48);
ctx.setFillStyle('red');
ctx.fillText('¥' + price, WIDTH / 2, 880 + contentHh);
ctx.draw(true, function() {
uni.canvasToTempFilePath({
canvasId: 'myCanvas',
fileType: 'png',
destWidth: WIDTH,
destHeight: HEIGHT,
success: function(res) {
uni.hideLoading();
successFn && successFn(res.tempFilePath);
},
fail: function(err) {
uni.hideLoading();
errFun && errFun(err);
}
})
});
},
fail: function(err) {
uni.hideLoading();
console.log('无法获取图片信息');
errFun && errFun(err);
}
})
}
生成海报获取文字
@param string text 为传入的文本
@param num 为单行显示的字节长度
@return array
textByteLength: function(text, num) {
let strLength = 0;
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] // [处理文字的总字节长度,每行显示内容的数组,行数]
},
调用
that.$util.PosterCanvas(arr2,name, price, function(
tempFilePath) {
console.log("成功,图片路径",tempFilePath)
}, (err) => {
console.log(err)
});
效果图