index.ts
1.72 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
import path from 'path-browserify'
export function resolveRoutePath(basePath: string, routePath?: string) {
return basePath ? path.resolve(basePath, routePath ?? '') : routePath ?? ''
}
/** 计算表格列宽 */
export const calcColumnWidth = (data, title, dataFont, titleFont, otherWidth = 0) => {
let titleW = measureTextWidth(title, titleFont || dataFont);
if (!data.length) {
if (titleW + otherWidth > 260) {
return 260;
}
if (titleW + otherWidth + 32 < 96) {
return 96;
}
return titleW + 32 + otherWidth;//20边距,+2px边框 + 10px间隙
}
let maxWidth = 0;
for (const d of data) {
let w = measureTextWidth(d, dataFont);
if (maxWidth < w) {
maxWidth = w;
}
if (maxWidth > 330) {
break;
}
}
if (maxWidth > 330) {
return 360;
}
if (titleW + otherWidth > maxWidth) {
maxWidth = titleW + otherWidth;
}
if (maxWidth + 32 < 96) {
return 96;
}
return maxWidth + 32;
}
const getOffscreenCanvas = function (): HTMLCanvasElement {
let canvas = document.getElementById('canvas');
if (canvas) {
return <HTMLCanvasElement>canvas;
}
canvas = document.createElement('canvas');
canvas.id = "canvas";
canvas.style.display = 'none';
document.body.appendChild(canvas);
return <HTMLCanvasElement>canvas;
};
export const measureTextWidth = (text, font): number => {
if (!text) { text = ''; }
if (!font) {
return 0;
}
let ctx = getOffscreenCanvas().getContext('2d');
if (!ctx) {
return 0;
}
let fontSize = font.fontSize, fontFamily = font.fontFamily, fontWeight = font.fontWeight;
ctx.font = [fontWeight, "".concat(fontSize, "px"), fontFamily]
.join(' ')
.trim();
return ctx.measureText("".concat(text)).width;
}