forked from pearmini/guess-word
-
Notifications
You must be signed in to change notification settings - Fork 0
/
helper.js
63 lines (50 loc) · 1.27 KB
/
helper.js
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
function debounce(fn) {
var timer = null;
return function () {
clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(this, arguments);
}, 150);
};
};
function unique(list) {
var arr = [];
var map = {};
for (var i = 0; i < list.length; i++) {
var element = list[i];
if (!map[element]) {
arr.push(element);
map[element] = 1;
}
}
return arr;
}
var measureTextSpan;
function createSpan() {
if (measureTextSpan) return measureTextSpan;
measureTextSpan = document.createElement('span');
// 不显示在视窗
measureTextSpan.style.visibility = 'hidden';
measureTextSpan.style.position = 'absolute';
measureTextSpan.style.display = 'inline';
measureTextSpan.style.left = '-1000px';
measureTextSpan.style.top = '-1000px';
document.body.appendChild(measureTextSpan);
return measureTextSpan
}
/**
* measure text By DOM
* @param text
* @param font
*/
function measureTextByDOM(text, font) {
// 先创建 span
var span = createSpan();
span.style.fontSize = font.fontSize + 'px';
span.style.fontFamily = font.fontFamily;
span.style.fontWeight = font.fontWeight;
span.style.fontStyle = font.fontStyle;
span.style.fontVariant = font.fontVariant;
span.innerHTML = text;
return span.clientWidth;
}