22
33var FontFace = require ( './FontFace' ) ;
44var FontUtils = require ( './FontUtils' ) ;
5+ var LineBreaker = require ( 'linebreak' ) ;
56
67var canvas = document . createElement ( 'canvas' ) ;
78var ctx = canvas . getContext ( '2d' ) ;
@@ -13,10 +14,6 @@ var _zeroMetrics = {
1314 lines : [ ]
1415} ;
1516
16- function splitText ( text ) {
17- return text . split ( ' ' ) ;
18- }
19-
2017function getCacheKey ( text , width , fontFace , fontSize , lineHeight ) {
2118 return text + width + fontFace . id + fontSize + lineHeight ;
2219}
@@ -49,6 +46,9 @@ module.exports = function measureText (text, width, fontFace, fontSize, lineHeig
4946 var words ;
5047 var tryLine ;
5148 var currentLine ;
49+ var breaker ;
50+ var bk ;
51+ var lastBreak ;
5252
5353 ctx . font = fontFace . attributes . style + ' ' + fontFace . attributes . weight + ' ' + fontSize + 'px ' + fontFace . family ;
5454 textMetrics = ctx . measureText ( text ) ;
@@ -63,27 +63,31 @@ module.exports = function measureText (text, width, fontFace, fontSize, lineHeig
6363 } else {
6464 // Break into multiple lines.
6565 measuredSize . width = width ;
66- words = splitText ( text ) ;
6766 currentLine = '' ;
68-
69- // This needs to be optimized!
70- while ( words . length ) {
71- tryLine = currentLine + words [ 0 ] + ' ' ;
67+ breaker = new LineBreaker ( text ) ;
68+
69+ while ( bk = breaker . nextBreak ( ) ) {
70+ var word = text . slice ( lastBreak ? lastBreak . position : 0 , bk . position ) ;
71+
72+ tryLine = currentLine + word ;
7273 textMetrics = ctx . measureText ( tryLine ) ;
73- if ( textMetrics . width > width ) {
74+ if ( textMetrics . width > width || ( lastBreak && lastBreak . required ) ) {
7475 measuredSize . height += lineHeight ;
7576 measuredSize . lines . push ( { width : lastMeasuredWidth , text : currentLine . trim ( ) } ) ;
76- currentLine = words [ 0 ] + ' ' ;
77+ currentLine = word ;
7778 lastMeasuredWidth = ctx . measureText ( currentLine . trim ( ) ) . width ;
7879 } else {
7980 currentLine = tryLine ;
8081 lastMeasuredWidth = textMetrics . width ;
8182 }
82- if ( words . length === 1 ) {
83- textMetrics = ctx . measureText ( currentLine . trim ( ) ) ;
84- measuredSize . lines . push ( { width : textMetrics . width , text : currentLine . trim ( ) } ) ;
85- }
86- words . shift ( ) ;
83+
84+ lastBreak = bk ;
85+ }
86+
87+ currentLine = currentLine . trim ( ) ;
88+ if ( currentLine . length > 0 ) {
89+ textMetrics = ctx . measureText ( currentLine ) ;
90+ measuredSize . lines . push ( { width : textMetrics , text : currentLine } ) ;
8791 }
8892 }
8993
0 commit comments