2
2
3
3
var FontFace = require ( './FontFace' ) ;
4
4
var FontUtils = require ( './FontUtils' ) ;
5
+ var LineBreaker = require ( 'linebreak' ) ;
5
6
6
7
var canvas = document . createElement ( 'canvas' ) ;
7
8
var ctx = canvas . getContext ( '2d' ) ;
@@ -13,10 +14,6 @@ var _zeroMetrics = {
13
14
lines : [ ]
14
15
} ;
15
16
16
- function splitText ( text ) {
17
- return text . split ( ' ' ) ;
18
- }
19
-
20
17
function getCacheKey ( text , width , fontFace , fontSize , lineHeight ) {
21
18
return text + width + fontFace . id + fontSize + lineHeight ;
22
19
}
@@ -49,6 +46,9 @@ module.exports = function measureText (text, width, fontFace, fontSize, lineHeig
49
46
var words ;
50
47
var tryLine ;
51
48
var currentLine ;
49
+ var breaker ;
50
+ var bk ;
51
+ var lastBreak ;
52
52
53
53
ctx . font = fontFace . attributes . style + ' normal ' + fontFace . attributes . weight + ' ' + fontSize + 'pt ' + fontFace . family ;
54
54
textMetrics = ctx . measureText ( text ) ;
@@ -63,27 +63,31 @@ module.exports = function measureText (text, width, fontFace, fontSize, lineHeig
63
63
} else {
64
64
// Break into multiple lines.
65
65
measuredSize . width = width ;
66
- words = splitText ( text ) ;
67
66
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 ;
72
73
textMetrics = ctx . measureText ( tryLine ) ;
73
- if ( textMetrics . width > width ) {
74
+ if ( textMetrics . width > width || ( lastBreak && lastBreak . required ) ) {
74
75
measuredSize . height += lineHeight ;
75
76
measuredSize . lines . push ( { width : lastMeasuredWidth , text : currentLine . trim ( ) } ) ;
76
- currentLine = words [ 0 ] + ' ' ;
77
+ currentLine = word ;
77
78
lastMeasuredWidth = ctx . measureText ( currentLine . trim ( ) ) . width ;
78
79
} else {
79
80
currentLine = tryLine ;
80
81
lastMeasuredWidth = textMetrics . width ;
81
82
}
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 } ) ;
87
91
}
88
92
}
89
93
0 commit comments