EaselJS的Text中文不会自动换行的问题

一开始还没发现这个问题,只是在想为什么设了textWidth却无法换行。去官方找例子,都是好的,到我这里就不行了。

最后才想起来自己的文本都是汉字,别人的都是英文。你妈嗨,怪不得

原来默认是根据英文单词中间的空格来换的,汉字的情况就gg了。。。

修改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:
				var words = str.split(/(\s|[\u4e00-\u9fa5]+)/);//按照中文和空格来分割
				var splitChineseWords = [];
				for(var wordIndex = 0; wordIndex < words.length; wordIndex++)
				{
					var chineseWordStr = words[wordIndex];
                                        if(chineseWordStr == "")
                                             continue;
					if((/([\u4e00-\u9fa5]+)/).test(chineseWordStr))
					{
						splitChineseWords = splitChineseWords.concat(chineseWordStr.split(""));//再把中文拆分成一个一个的
					}
					else
					{
						splitChineseWords.push(chineseWordStr);
					}
				}
				words = splitChineseWords;//重新组成数组
				str = words[0];
				w = ctx.measureText(str).width;

				for (var j=1, jl=words.length; j<jl; j+=2) {
					// Line needs to wrap:
					var wordW = ctx.measureText(words[j] + words[j+1]).width;
					if (w + wordW > this.lineWidth) {
                                               if(words[j] != "\s") //原版没有这个IF,
                                                   str += words[j]; //英文时为空格,不需要加,中文时为汉字,所以不能漏了
						if (paint) { this._drawTextLine(ctx, str, count*lineHeight); }
						if (lines) { lines.push(str); }
						if (w > maxW) { maxW = w; }
						str = words[j+1];
						w = ctx.measureText(str).width;
						count++;
					} else {
						str += words[j] + words[j+1];
						w += wordW;
					}
				}
			}

			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;
	};


你可能感兴趣的:(createjs)