From 2541b7b69b1259786ceac929badc120aa3d869e5 Mon Sep 17 00:00:00 2001 From: Ulrich Sossou Date: Sun, 24 Aug 2014 15:34:27 +0100 Subject: [PATCH] Properly calculate width of whitespace characters when text is justified --- src/shapes/itext.class.js | 41 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/src/shapes/itext.class.js b/src/shapes/itext.class.js index bcdc3e00..b76600a7 100644 --- a/src/shapes/itext.class.js +++ b/src/shapes/itext.class.js @@ -971,6 +971,10 @@ * @param {CanvasRenderingContext2D} ctx Context to render on */ _getWidthOfChar: function(ctx, _char, lineIndex, charIndex) { + if (this.textAlign === 'justify' && /\s/.test(_char)) { + return this._getWidthOfSpace(ctx, lineIndex); + } + var styleDeclaration = this._getStyleDeclaration(lineIndex, charIndex); this._applyFontStyles(styleDeclaration); var cacheProp = this._getCacheProp(_char, styleDeclaration); @@ -1040,6 +1044,43 @@ return this._getWidthOfCharsAt(ctx, lineIndex, textLines[lineIndex].length, textLines); }, + /** + * @private + * @param {CanvasRenderingContext2D} ctx Context to render on + * @param {Number} lineIndex + */ + _getWidthOfSpace: function (ctx, lineIndex) { + var lines = this.text.split(this._reNewline); + var line = lines[lineIndex]; + var words = line.split(/\s+/); + var wordsWidth = this._getWidthOfWords(ctx, line, lineIndex); + var widthDiff = this.width - wordsWidth; + var numSpaces = words.length - 1; + var width = widthDiff / numSpaces; + + return width; + }, + + /** + * @private + * @param {CanvasRenderingContext2D} ctx Context to render on + * @param {Number} line + * @param {Number} lineIndex + */ + _getWidthOfWords: function (ctx, line, lineIndex) { + var width = 0; + + for (var charIndex = 0; charIndex < line.length; charIndex++) { + var _char = line[charIndex]; + + if (!_char.match(/\s/)) { + width += this._getWidthOfChar(ctx, _char, lineIndex, charIndex); + } + }; + + return width; + }, + /** * @private * @param {CanvasRenderingContext2D} ctx Context to render on