-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathget-text-width.ts
More file actions
52 lines (40 loc) · 1.31 KB
/
get-text-width.ts
File metadata and controls
52 lines (40 loc) · 1.31 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
import { theme } from "@/themes/federal";
let canvas: HTMLCanvasElement;
let ctx: CanvasRenderingContext2D;
const fontFamily = theme.typography.fontFamily as string;
export const getTextWidth = (text: string, options: { fontSize: number }) => {
if (canvas === undefined && ctx === undefined) {
canvas = document.createElement("canvas");
ctx = canvas.getContext("2d") as CanvasRenderingContext2D;
}
ctx.font = `${options.fontSize}px ${fontFamily}`;
return ctx.measureText(text).width;
};
export const getTextHeight = (
text: string,
options: {
fontSize: number;
width?: number;
lineHeight?: number | string;
}
) => {
const measureDiv = document.createElement("div");
measureDiv.style.font = `${options.fontSize}px ${fontFamily}`;
measureDiv.style.position = "absolute";
measureDiv.style.visibility = "hidden";
measureDiv.style.lineHeight = options.lineHeight
? typeof options.lineHeight === "number"
? `${options.lineHeight}px`
: options.lineHeight
: "normal";
if (options.width) {
measureDiv.style.width = `${options.width}px`;
} else {
measureDiv.style.whiteSpace = "nowrap";
}
measureDiv.textContent = text;
document.body.appendChild(measureDiv);
const height = measureDiv.offsetHeight;
document.body.removeChild(measureDiv);
return height;
};