在这里插入代码片
**/**
* @数组内容canvas图片上换行
* @temp数组字符串 ['是读书读书读','圣诞节四点九四级']
* @context //uni.createCanvasContext('myCanvas', this);
* // let context = uni.createCanvasContext('myCanvas', this);
*@lns控制单条字符串换行的行数
*/**
export const canvasMeasureText = (temp,context,lns) => {
let tabindex = 0
console.log(temp)
for(let i = 0; i < temp.length; i++) {
const txtTemp = temp[i].replace(/\s*/g,"")
// console.log("执行了3333。。。")
// console.log("i.length======》。",i,i.length)
// console.log("temp【i】.length======》。",txtTemp,txtTemp.length)
// const text = '这是要换行的文本内容';
const maxWidth = 80; // 最大宽度,超过该宽度则换行
const lineHeight = 7; // 行高
const breakTextLines = (txtTemp, maxWidth) => {
const words = txtTemp.split('');
let line = '';
const lines = [];
for (let i = 0; i < words.length; i++) {
const word = words[i];
const testLine = line + word;
const metrics = context.measureText(testLine);
if (metrics.width > maxWidth && i > 0) {
lines.push(line);
line = word;
} else {
line = testLine;
}
}
lines.push(line);
return lines;
};
const lines = breakTextLines(txtTemp, maxWidth);
lines.forEach((line, index) => {
context.setFontSize(4)
tabindex = tabindex +1
context.fillText(line, 0, tabindex * lineHeight);
console.log('tabindex=====》',tabindex,'=======》',context.fillText(line, 0, tabindex * lineHeight))
});
console.log("执行了4444。。。")
// tabindex=0
}
tabindex=0
}
uni canvas 文字换行(多行)方法
最新推荐文章于 2024-07-19 18:35:18 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)