forked from joshmarinacci/node-pureimage
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtext.ts
More file actions
237 lines (219 loc) · 5.63 KB
/
Copy pathtext.ts
File metadata and controls
237 lines (219 loc) · 5.63 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
import * as opentype from "opentype.js";
import type { Context } from "./context.js";
import { TextAlign, TextBaseline } from "./types.js";
/** Map containing all the fonts available for use */
const _fonts: Record<string, RegisteredFont> = {};
/** The default font family to use for text */
// const DEFAULT_FONT_FAMILY = 'source';
export type Font = {
/** The font family to set */
family: string;
/** An integer representing the font size to use */
size?: number;
binary?: string | Buffer | ArrayBuffer | Uint8Array;
weight?: number;
style?: string;
variant?: string;
loaded?: boolean;
font?: opentype.Font | null;
load?: (cb: CallableFunction) => void;
loadSync?: () => Font;
loadPromise?: () => Promise<void>;
};
class RegisteredFont {
fontData: Buffer | ArrayBuffer | Uint8Array;
family: string;
weight: number;
style: string;
variant: string;
loaded: boolean;
font: opentype.Font;
constructor(
fontData: Buffer | ArrayBuffer | Uint8Array,
family: string,
weight?: number,
style?: string,
variant?: string,
) {
this.fontData = fontData;
this.family = family;
this.weight = weight;
this.style = style;
this.variant = variant;
this.loaded = false;
this.font = null;
}
_load(cb: () => void) {
if (this.loaded) {
if (cb) cb();
return;
}
try {
// Use opentype.parse to load the font from buffer
this.font = opentype.parse(this.fontData);
this.loaded = true;
if (cb) cb();
} catch (err) {
throw new Error("Could not parse font data: " + err);
}
}
loadSync() {
if (this.loaded) {
return this;
}
try {
// Synchronously parse the font data
this.font = opentype.parse(this.fontData);
this.loaded = true;
return this;
} catch (err) {
throw new Error("Could not load font: " + err);
}
}
load() {
return this.loadPromise();
}
loadPromise() {
return new Promise<void>((resolve, reject) => {
try {
this._load(() => resolve());
} catch (err) {
reject(err);
}
});
}
}
/**
* Register Font
*
* @returns Font instance
*/
export function registerFont(
/** Font data as Buffer, ArrayBuffer, or Uint8Array */
fontData: Buffer | ArrayBuffer | Uint8Array,
/** The name to give the font */
family: string,
/** The font weight to use */
weight?: number,
/** Font style */
style?: string,
/** Font variant */
variant?: string,
) {
_fonts[family] = new RegisteredFont(
fontData,
family,
weight,
style,
variant,
);
return _fonts[family];
}
/**@ignore */
export const debug_list_of_fonts = _fonts;
/**
* Find Font
*
* Search the `fonts` array for a given font family name
*/
function findFont(
/** The name of the font family to search for */
family: string,
): RegisteredFont | undefined {
if (_fonts[family]) return _fonts[family];
family = Object.keys(_fonts)[0];
return _fonts[family];
}
/** Process Text Path */
export function processTextPath(
/** The {@link Context} to paint on */
ctx: Context,
/** The text to write to the given Context */
text: string,
/** X position */
x: number,
/** Y position */
y: number,
/** Indicates whether or not the font should be filled */
fill: boolean,
hAlign: TextAlign,
vAlign: TextBaseline,
) {
const font = findFont(ctx._font.family);
if (!font) {
// eslint-disable-next-line no-console
console.warn("Font missing", ctx._font);
return;
}
const metrics = measureText(ctx, text);
/* if(hAlign === 'start' || hAlign === 'left') x = x; */
if (hAlign === "end" || hAlign === "right") x = x - metrics.width;
if (hAlign === "center") x = x - metrics.width / 2;
/* if(vAlign === 'alphabetic') y = y; */
if (vAlign === "top") y = y + metrics.emHeightAscent;
if (vAlign === "middle")
y = y + metrics.emHeightAscent / 2 + metrics.emHeightDescent / 2;
if (vAlign === "bottom") y = y + metrics.emHeightDescent;
const size = ctx._font.size;
if (!font.loaded) {
console.warn("font not loaded yet", ctx._font);
return;
}
const path = font.font.getPath(text, x, y, size);
ctx.beginPath();
path.commands.forEach(function (cmd) {
switch (cmd.type) {
case "M":
ctx.moveTo(cmd.x, cmd.y);
break;
case "Q":
ctx.quadraticCurveTo(cmd.x1, cmd.y1, cmd.x, cmd.y);
break;
case "L":
ctx.lineTo(cmd.x, cmd.y);
break;
case "C":
ctx.bezierCurveTo(cmd.x1, cmd.y1, cmd.x2, cmd.y2, cmd.x, cmd.y);
break;
case "Z": {
ctx.closePath();
fill ? ctx.fill() : ctx.stroke();
ctx.beginPath();
break;
}
}
});
}
type TextMetrics = {
width: number;
emHeightAscent: number;
emHeightDescent: number;
};
/** Measure Text */
export function measureText(
/** The {@link Context} to paint on */
ctx: Context,
/** The text to measure */
text: string,
): TextMetrics {
const font = findFont(ctx._font.family);
if (!font) {
console.warn("WARNING. Can't find font family ", ctx._font);
return { width: 10, emHeightAscent: 8, emHeightDescent: 2 };
}
if (!font.font) {
console.warn("WARNING. Can't find font family ", ctx._font);
return { width: 10, emHeightAscent: 8, emHeightDescent: 2 };
}
const fsize = ctx._font.size;
const glyphs = font.font.stringToGlyphs(text);
let advance = 0;
glyphs.forEach(function (g) {
advance += g.advanceWidth;
});
return {
width: (advance / font.font.unitsPerEm) * fsize,
emHeightAscent: (font.font.ascender / font.font.unitsPerEm) * fsize,
emHeightDescent: (font.font.descender / font.font.unitsPerEm) * fsize,
};
}