以uni-app框架为例:可以把画图封装成一个函数调用。
activityCanvas: function(arrImages, storeName, price, people, count, successFn) {
let that = this;
let rain = 2;
const context = uni.createCanvasContext('activityCanvas');
context.clearRect(0, 0, 0, 0);
/**
* 只能获取合法域名下的图片信息,本地调试无法获取
*
*/
context.fillStyle = '#fff';
context.fillRect(0, 0, 594, 850);
uni.getImageInfo({
src: arrImages[0],
success: function(res) {
context.drawImage(arrImages[0], 0, 0, 594, 850);
context.setFontSize(14*rain);
context.setFillStyle('#333333');
// 绘制文字自动换行
that.canvasWraptitleText(context, storeName, 112*rain, 110*rain, 250*rain, 30*rain, 1*rain)
... // 这里可绘制自己项目的内容
context.draw(true, function() {
uni.canvasToTempFilePath({
canvasId: 'activityCanvas',
fileType: 'png',
destWidth: 594,
destHeight: 850,
success: function(res) {
// uni.hideLoading();
successFn && successFn(res.tempFilePath);
}
})
});
},
fail: function(err) {
console.log('失败', err)
uni.hideLoading();
that.Tips({
title: '无法获取图片信息'
});
}
})
},
文字超出显示省略号单独封装一个函数调用。
/**
* 绘制文字自动换行
* @param array arr2 海报素材
* @param Number x , y 绘制的坐标
* @param Number maxWigth 绘制文字的宽度
* @param Number lineHeight 行高
* @param Number maxRowNum 最大行数
*/
canvasWraptitleText(canvas, text, x, y, maxWidth, lineHeight, maxRowNum) {
if (typeof text != 'string' || typeof x != 'number' || typeof y != 'number') {
return;
}
// canvas.font = '20px Bold PingFang SC'; //绘制文字的字号和大小
// 字符分隔为数组
var arrText = text.split('');
var line = '';
var rowNum = 1
for (var n = 0; n < arrText.length; n++) {
var testLine = line + arrText[n];
var metrics = canvas.measureText(testLine);
var testWidth = metrics.width;
if (testWidth > maxWidth && n > 0) {
if (rowNum >= maxRowNum) {
var arrLine = testLine.split('')
arrLine.splice(-9)
var newTestLine = arrLine.join("")
newTestLine += "..."
canvas.fillText(newTestLine, x, y);
//如果需要在省略号后面添加其他的东西,就在这个位置写(列如添加扫码查看详情字样)
//canvas.fillStyle = '#2259CA';
//canvas.fillText('扫码查看详情',x + maxWidth-90, y);
return
}
canvas.fillText(line, x, y);
line = arrText[n];
y += lineHeight;
rowNum += 1
} else {
line = testLine;
}
}
canvas.fillText(line, x, y);
}