-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtext-width.js
More file actions
76 lines (59 loc) · 2.18 KB
/
text-width.js
File metadata and controls
76 lines (59 loc) · 2.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
(function (window, document) {
window.TextWidth = TextWidth;
if (typeof window.define === 'function' && window.define.amd) {
window.define('TextWidth', [], function() {
return window.TextWidth;
});
}
var SPLIT_RE = /\s+/;
var DEFAULT_OPTIONS = {
fontFamily: 'Arial',
fontSize: '12px'
};
function TextWidth(options) {
this.options = options || DEFAULT_OPTIONS;
}
TextWidth.prototype.single = singleLine;
TextWidth.prototype.multi = multiLine;
function singleLine(text, fontFamily, fontSize) {
fontFamily = fontFamily || this.options.fontFamily;
fontSize = fontSize || this.options.fontSize;
var span = prepareContainer(fontFamily, fontSize);
span.innerHTML = text.trim();
document.body.appendChild(span);
var width = span.clientWidth;
document.body.removeChild(span);
return width;
}
function multiLine(text, fontFamily, fontSize, maxWidth) {
fontFamily = fontFamily || this.options.fontFamily;
fontSize = fontSize || this.options.fontSize;
maxWidth = maxWidth || Infinity;
var testStr = '';
var width = 0;
var lines = 0;
var lineWidth = [];
text.trim().split(SPLIT_RE).forEach(function (part) {
//TODO: consider strings with multiple spaces & tabs
var space = testStr ? ' ' : '';
testStr += space + part;
width = singleLine(testStr, fontFamily, fontSize);
if (width > maxWidth) {
lines++;
testStr = part;
width = singleLine(testStr, fontFamily, fontSize);
}
lineWidth[lines] = width;
});
return lineWidth;
}
function prepareContainer(fontFamily, fontSize) {
this.container = this.container || document.createElement('span');
var containerStyle = this.container.style;
containerStyle.fontFamily = fontFamily;
containerStyle.fontSize = fontSize;
containerStyle.whiteSpace = 'nowrap';
containerStyle.visibility = 'hidden';
return this.container;
}
})(window, document);