將文字包裝成段落
當達到所需的最大寬度時,Native Canvas API 沒有將文字換行到下一行的方法。此示例將文字包裝為段落。
function wrapText(text, x, y, maxWidth, fontSize, fontFace){
var firstY=y;
var words = text.split(' ');
var line = '';
var lineHeight=fontSize*1.286; // a good approx for 10-18px sizes
ctx.font=fontSize+" "+fontFace;
ctx.textBaseline='top';
for(var n = 0; n < words.length; n++) {
var testLine = line + words[n] + ' ';
var metrics = ctx.measureText(testLine);
var testWidth = metrics.width;
if(testWidth > maxWidth) {
ctx.fillText(line, x, y);
if(n<words.length-1){
line = words[n] + ' ';
y += lineHeight;
}
}
else {
line = testLine;
}
}
ctx.fillText(line, x, y);
}