-
Notifications
You must be signed in to change notification settings - Fork 0
/
dom.ts
38 lines (30 loc) · 852 Bytes
/
dom.ts
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
import { Font } from './types';
let span;
function createSpan() {
if (span) return;
span = document.createElement('span');
// 不显示在视窗
span.style.visibility = 'hidden';
span.style.position = 'absolute';
span.style.display = 'inline';
span.style.left = '-1000px';
span.style.top = '-1000px';
document.body.appendChild(span);
}
/**
* measure text By DOM
* @param text
* @param font
*/
export function measureTextByDOM(text: string, font: Font): number {
// 先创建 span
createSpan();
const { fontSize, fontFamily, fontWeight, fontStyle, fontVariant } = font;
span.style.fontSize = `${fontSize}px`;
span.style.fontFamily = fontFamily;
span.style.fontWeight = fontWeight;
span.style.fontStyle = fontStyle;
span.style.fontVariant = fontVariant;
span.innerHTML = text;
return span.clientWidth;
}