Properly calculate width of whitespace characters when text is justified

This commit is contained in:
Ulrich Sossou 2014-08-24 15:34:27 +01:00
parent 605946b47b
commit 2541b7b69b

View file

@ -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