上次項(xiàng)目中,涉及到文字換行的問題,如圖

可謂將換行做到了極致
解決方法:
將文字換行封裝為一個(gè)方法
/**
* 海報(bào)文字換行
*/
fillTextWrap(ctx, text, x, y, maxWidth, lineHeight) {
// 設(shè)定默認(rèn)最大寬度
const systemInfo = wx.getSystemInfoSync()
const deciveWidth = systemInfo.screenWidth
// 默認(rèn)參數(shù)
maxWidth = maxWidth || deciveWidth
lineHeight = lineHeight || 20
// 校驗(yàn)參數(shù)
if (
typeof text !== 'string' ||
typeof x !== 'number' ||
typeof y !== 'number'
) {
return
}
// 字符串分割為數(shù)組
const arrText = text.split('')
// 當(dāng)前字符串及寬度
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)
}
}
調(diào)用方法繪制文字
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,問題得到解決希望能幫到你們