diff --git a/CanvasTextWrapper.js b/CanvasTextWrapper.js index 8a73d3b..705b141 100644 --- a/CanvasTextWrapper.js +++ b/CanvasTextWrapper.js @@ -57,14 +57,15 @@ }; if (this.sizeToFill) { - // starting at 1px increase font size by 1px until text block exceeds the height of its padded container + // starting at 1px increase font size by 1px until text block exceeds the height of its padded container or until words break var elementHeight = ((this.fitParent === false) ? this.canvas.height : this.canvas.parentNode.clientHeight) - (this.paddingX * 2); + var numWords = this.text.trim().split(/\s+/).length; var fontSize = 0; do { this.setFontSize(++fontSize); var lines = this.getWrappedText(elementWidth); var textBlockHeight = lines.length * this.lineHeight; - } while (textBlockHeight < elementHeight); + } while (textBlockHeight < elementHeight && lines.join(' ').split(/\s+/).length == numWords); // use previous font size, not the one that broke the while condition this.setFontSize(--fontSize); @@ -93,7 +94,7 @@ getWrappedText: function(elementWidth) { var maxTextLength = elementWidth - (this.paddingX * 2); - var words = this.text.split(/\s+/); + var words = this.text.trim().split(/\s+/); var lines = []; this.checkWordsLength(this.context, words, maxTextLength); diff --git a/CanvasTextWrapper.min.js b/CanvasTextWrapper.min.js index 45e4fde..3d652df 100644 --- a/CanvasTextWrapper.min.js +++ b/CanvasTextWrapper.min.js @@ -4,4 +4,4 @@ * MIT License (http://www.opensource.org/licenses/mit-license.html) * Copyright (c) 2014 Vadim Namniak */ -!function(){"use strict";var a={font:"18px Arial, sans-serif",textAlign:"left",verticalAlign:"top",paddingX:0,paddingY:0,fitParent:!1,lineBreak:"auto",sizeToFill:!1};window.CanvasTextWrapper=function(b,c,d){if(!(this instanceof CanvasTextWrapper))throw new TypeError('CanvasTextWrapper constructor failed. Use "new" keyword when instantiating.');this.canvas=b,this.text=c;for(var e in a)this[e]=d&&d[e]?d[e]:a[e];this.lineHeight=parseInt(this.font.replace(/^\D+/g,""),10),this.validate(),this.context=this.canvas.getContext("2d"),this.context.font=this.font,this.context.textBaseline="bottom",this.drawText()},CanvasTextWrapper.prototype={drawText:function(){var a=this.fitParent===!1?this.canvas.width:this.canvas.parentNode.clientWidth,b={x:0,y:0};if(this.sizeToFill){var c=(this.fitParent===!1?this.canvas.height:this.canvas.parentNode.clientHeight)-2*this.paddingX,d=0;do{this.setFontSize(++d);var e=this.getWrappedText(a),f=e.length*this.lineHeight}while(c>f);this.setFontSize(--d)}var e=this.getWrappedText(a),f=e.length*this.lineHeight;this.setTextVerticalAlign(b,f);for(var g=0;gc){for(var g=0;a.measureText(e+b[d][g]).width<=c&&gg&&f.join(" ").split(/\s+/).length==d);this.setFontSize(--e)}var f=this.getWrappedText(a),g=f.length*this.lineHeight;this.setTextVerticalAlign(b,g);for(var h=0;hc){for(var g=0;a.measureText(e+b[d][g]).width<=c&&g