上次项目中,涉及到文字换行的问题,如图
可谓将换行做到了极致
解决方法:
将文字换行封装为一个方法
/**
* 海报文字换行
*/
fillTextWrap(ctx, text, x, y, maxWidth, lineHeight) {
// 设定默认最大宽度
const systemInfo = wx.getSystemInfoSync()
const deciveWidth = systemInfo.screenWidth
// 默认参数
maxWidth = maxWidth || deciveWidth
lineHeight = lineHeight || 20
// 校验参数
if (
typeof text !== 'string' ||
typeof x !== 'number' ||
typeof y !== 'number'
) {
return
}
// 字符串分割为数组
const arrText = text.split('')
// 当前字符串及宽度
let currentText = ''
let currentWidth
for (let letter of arrText) {
currentText += letter
currentWidth = ctx.measureText(currentText).width
if (currentWidth > maxWidth) {
ctx.fillText(currentText, x, y)
currentText = ''
y += lineHeight
}
}
if (currentText) {
ctx.fillText(currentText, x, y)
}
}
调用方法绘制文字
ctx.setFillStyle('red')
ctx.setFontSize(26)
// ctx.setTextAlign('center')
//使文字换行显示
const textHeightL = that.fillTextWrap(
ctx,
that.renderData.springScrolls.L,
50,
313-(that.renderData.springScrolls.L).length*26/2, //为了让文字垂直居中
18,
36
)
const textHeightR = that.fillTextWrap(
ctx,
that.renderData.springScrolls.R,
275,
313-(that.renderData.springScrolls.R).length*26/2,//为了让文字垂直居中
18,
36
)
OK,问题得到解决希望能帮到你们