fillTextWithMaxWidth
This commit is contained in:
parent
dae1ace3ff
commit
fa46aef44b
@ -1616,9 +1616,10 @@ core.clearMap(name)
|
||||
该函数的name也可以是'all',若为'all'则为清空所有系统画布。
|
||||
|
||||
|
||||
core.fillText(name, text, x, y, style, font)
|
||||
core.fillText(name, text, x, y, style, font, maxWidth)
|
||||
在某个画布上绘制一段文字。
|
||||
text为要绘制的文本,x,y为要绘制的坐标,style可选为绘制的样式,font可选为绘制的字体。(下同)
|
||||
如果maxWidth不为null,则视为文字最大宽度,如果超过此宽度则会自动放缩文字直到自适应为止。
|
||||
请注意textAlign和textBaseline将决定绘制的左右对齐和上下对齐方式。
|
||||
具体可详见core.setTextAlign()和core.setTextBaseline()函数。
|
||||
|
||||
|
||||
23
libs/ui.js
23
libs/ui.js
@ -53,11 +53,30 @@ ui.prototype.clearMap = function (name, x, y, width, height) {
|
||||
}
|
||||
|
||||
////// 在某个canvas上绘制一段文字 //////
|
||||
ui.prototype.fillText = function (name, text, x, y, style, font) {
|
||||
ui.prototype.fillText = function (name, text, x, y, style, font, maxWidth) {
|
||||
if (style) core.setFillStyle(name, style);
|
||||
if (font) core.setFont(name, font);
|
||||
var ctx = this.getContextByName(name);
|
||||
if (ctx) ctx.fillText(text, x, y);
|
||||
if (ctx) {
|
||||
// 如果存在最大宽度
|
||||
if (maxWidth != null)
|
||||
this._fillTextWithMaxWidth(ctx, text, x, y, maxWidth);
|
||||
else
|
||||
ctx.fillText(text, x, y);
|
||||
}
|
||||
}
|
||||
|
||||
////// 自适配字体大小
|
||||
ui.prototype._fillTextWithMaxWidth = function (ctx, text, x, y, maxWidth) {
|
||||
// 获得当前字体
|
||||
var font = ctx.font, u = /(\d+)px/.exec(font);
|
||||
if (u == null) return ctx.fillText(text, x, y);
|
||||
for (var font_size = parseInt(u[1]); font_size >= 8; font_size--) {
|
||||
ctx.font = font.replace(/(\d+)px/, font_size+"px");
|
||||
if (ctx.measureText(text).width <= maxWidth) break;
|
||||
}
|
||||
ctx.fillText(text, x, y);
|
||||
ctx.font = font;
|
||||
}
|
||||
|
||||
////// 在某个canvas上绘制粗体 //////
|
||||
|
||||
Loading…
Reference in New Issue
Block a user