可根据实际情况自己调整
onLoad() {
this.getShuiYin()
},
async getShuiYin(){
//text:传入的字符串(需要换行,则:'第一行\n第二行')
//15:字号
//#ddd:字体颜色
let shuiyinImg = await util.textToImg(text, 15, '#ddd')
this.setData({
shuiyinBg: `url("${shuiyinImg}")`,
})
}
const textToImg = function (text, fontsize, fontcolor) {
return new Promise(resolve => {
let buHeight = 0;
if (fontsize <= 32) {
buHeight = 99;
} else if (fontsize > 32 && fontsize <= 60) {
buHeight = 2;
} else if (fontsize > 60 && fontsize <= 80) {
buHeight = 4;
} else if (fontsize > 80 && fontsize <= 100) {
buHeight = 6;
} else if (fontsize > 100) {
buHeight = 10;
}
const lines = text.split('\n');
let height = fontsize + buHeight + (lines.length - 1) * fontsize;
wx.createSelectorQuery()
.select('#canvas')
.fields({
node: true,
size: true,
})
.exec(function (res) {
console.log('res', res)
const canvas = res[0].node
canvas.padding = 30;
const context = canvas.getContext('2d')
context.clearRect(0, 0, canvas.width * 2, canvas.height);
context.textAlign = "center"; // 设置文本居中对齐
// 计算文本的宽度
let textWidth = 0;
lines.forEach(line => {
const lineWidth = context.measureText(line).width;
if (lineWidth > textWidth) {
textWidth = lineWidth;
}
});
canvas.width = textWidth + 80; // 根据文本的宽度调整画布宽度
canvas.height = height;
context.fillStyle = fontcolor;
context.font = fontsize + "px Arial";
context.textBaseline = 'middle';
let y = fontsize / 2;
lines.forEach(line => {
const lineWidth = context.measureText(line).width;
const x = canvas.width / 2 - lineWidth / 2; // 计算每行文本的x坐标位置
context.fillText(line, x, y);
y += fontsize;
});
console.log('canvas', canvas)
var dataUrl = canvas.toDataURL('image/png');
resolve(dataUrl)
}.bind(this))
})
}