之前就提到过createjs中Text中文不换行的问题,之前的解决方法是在中文之间加空格。由于项目中要用到,加空格的方法不合适,所以自己改了一下源码。
修改了easeljs中的p._drawText方法,代码如下。
/**
* Draws multiline text.
* @method _drawText
* @param {CanvasRenderingContext2D} ctx
* @param {Object} o
* @param {Array} lines
* @return {Object}
* @protected
**/
p._drawText = function(ctx, o, lines) {
var paint = !!ctx;
if (!paint) {
ctx = Text._workingContext;
ctx.save();
this._prepContext(ctx);
}
var lineHeight = this.lineHeight||this.getMeasuredLineHeight();
var maxW = 0, count = 0;
var hardLines = String(this.text).split(/(?:\r\n|\r|\n)/);
for (var i=0, l=hardLines.length; i<l; i++) {
var str = hardLines[i];
var w = null;
if (this.lineWidth != null && (w = ctx.measureText(str).width) > this.lineWidth) {
// text wrapping:
// hanyeah 实现中文换行
var words0 ;
var words ;
if((/[\u4e00-\u9fa5]+/).test(str)){ //含有中文
words0=str.split(/(\s)/);
words=[];
for(var hi=0;hi<words0.length;hi++){
var hs="";
for(var hj=0;hj<words0[hi].length;hj++){
var hjs=words0[hi][hj];
if(hjs.charCodeAt(0)>255){
if(hs!=""){
words.push(hs);
}
words.push(hjs);
hs="";
}
else{
hs+=hjs;
}
}
if(hs!=""){
words.push(hs);
}
}
}
else{
words = str.split(/(\s)/);
}
str = words[0];
w = ctx.measureText(str).width;
for (var j=1, jl=words.length; j<jl; j+=1) {
// Line needs to wrap:
var wordW = ctx.measureText(words[j]).width;
if (w + wordW > this.lineWidth) {
if (paint) { this._drawTextLine(ctx, str, count*lineHeight); }
if (lines) { lines.push(str); }
if (w > maxW) { maxW = w; }
str = words[j];
w = ctx.measureText(str).width;
count++;
} else {
str += words[j];
w += wordW;
}
}
}
//end hanyeah 实现中文换行
if (paint) { this._drawTextLine(ctx, str, count*lineHeight); }
if (lines) { lines.push(str); }
if (o && w == null) { w = ctx.measureText(str).width; }
if (w > maxW) { maxW = w; }
count++;
}
if (o) {
o.width = maxW;
o.height = count*lineHeight;
}
if (!paint) { ctx.restore(); }
return o;
};
评论列表:
cfg.ctx.save();
ext(cfg.ctx, opt, true);
var tmp = '';
for(var i = 1; i < s.length; i++){
if(cfg.ctx.measureText(s.substr(0, i)).width > opt.lineWidth){
tmp += s.substr(0, i - 1) + '\n';
s = s.substr(i - 1);
i = 1;
}
}
cfg.ctx.restore();
return tmp;
}
这样就可以不修改源代码了
我看function txt_fmt(s, opt)的大概意思是:自己对字符串进行处理逐个读取字符,进行分行,返回分行后的字符串。不知道理解的对不对。
简单的这样做可以,但是存在两个问题:
1、中英文混排的情况,英文单词中间不换行,这种方法不能处理;
2、字符串中本身就有"\n",也没有考虑进去。
基本思路都是一样的,要适应的情况越多,代码也就越复杂。