function drawTextLine(ctx, text, x, y){
let lines = text.split('');
let lineCount = 0;
var lineHeight = 25
var maxHeight = 200
let newLines = JSON.parse(JSON.stringify(lines))
let currentString= ''
for (var line=0; line<=lines.length;line++) {
let textHeight = lineCount * lineHeight
if(textHeight < maxHeight){
currentString = newLines.splice(0,1).join('')
ctx.strokeText(currentString, x, y + (lineCount+1) * lineHeight)
ctx.fillText(currentString, x, y + (lineCount+1) * lineHeight);
lineCount++;
} else {
lineCount = 0
x = x - 30
}
}
}
调用
const ctx = canvas.getContext('2d');
let text = '今天非常开心,希望每天如此呀'
drawTextLine(ctx, text, x,y);