canvas绘制文字自动换行
// canvas绘制文字自动换行
CanvasRenderingContext2D.prototype.wrapText = function (text, x, y, maxWidth, lineHeight) {
// 判断传参是否合法
if (typeof text != 'string' || typeof x != 'number' || typeof y != 'number') {
return;
}
// 获取canvasrenderingcontext2d对象
var context = this;
// 获取当前操作canvas元素
var canvas = context.canvas;
// 如果没有传递最大宽度,则设置默认最大宽度
if (typeof maxWidth == 'undefined') {
// canvas存在就设置为canvas的宽度,否则默认300
maxWidth = (canvas && canvas.width) || 300;
}
// 字符分隔为数组
var arrText = text.split('');
var line = '';
for (var n = 0; n < arrText.length; n++) {
var testLine = line + arrText[n];
var metrics = context.measureText(testLine);
var testWidth = metrics.width;
// 如果没有传递行高,则设置默认行高
if (typeof lineHeight == 'undefined' || lineHeight === 0) {
lineHeight = metrics.actualBoundingBoxAscent + metrics.actualBoundingBoxDescent
lineHeight = lineHeight * 1.2
}
// 如果测量出来的宽度大于最大宽度且不是第一个字符
// 则渲染未填充当前字符的行,然后开始新的行将当前字符填充进去
if (testWidth > maxWidth && n > 0) {
context.fillText(line, x, y);
line = arrText[n];
y += lineHeight;
} else {
line = testLine;
}
}
context.fillText(line, x, y);
};
本作品采用 知识共享署名-相同方式共享 4.0 国际许可协议 进行许可。