@@ -14,16 +14,30 @@ const FONT_REGISTER: Record<string, opentype.Font> = {};
14
14
*
15
15
* The font should be in TTF
16
16
*/
17
- export const loadFont = async ( fontPath : string , fontFamily = "default" ) => {
18
- // @ts -expect-error missing info in the types
19
- const font : opentype . Font = await opentype . load ( fontPath , null , {
20
- isUrl : true ,
21
- } ) ;
17
+ export async function loadFont (
18
+ fontPath : string | ArrayBuffer ,
19
+ fontFamily = "default" ,
20
+ force = false
21
+ ) {
22
+ if ( ! force && FONT_REGISTER [ fontFamily ] ) {
23
+ console . log ( `Font ${ fontFamily } already loaded` ) ;
24
+ return FONT_REGISTER [ fontFamily ] ;
25
+ }
26
+
27
+ let fontData : ArrayBuffer ;
28
+ if ( typeof fontPath === "string" ) {
29
+ const response = await fetch ( fontPath ) ;
30
+ fontData = await response . arrayBuffer ( ) ;
31
+ } else {
32
+ fontData = fontPath ;
33
+ }
34
+
35
+ const font : opentype . Font = opentype . parse ( fontData ) ;
22
36
FONT_REGISTER [ fontFamily ] = font ;
23
37
if ( ! FONT_REGISTER . default ) FONT_REGISTER . default = font ;
24
38
25
39
return font ;
26
- } ;
40
+ }
27
41
28
42
export const getFont = ( fontFamily = "default" ) => {
29
43
return FONT_REGISTER [ fontFamily ] ;
@@ -88,7 +102,13 @@ export function textBlueprints(
88
102
text : string ,
89
103
{ startX = 0 , startY = 0 , fontSize = 16 , fontFamily = "default" } = { }
90
104
) : Blueprints {
91
- const font = getFont ( fontFamily ) ;
105
+ let font = getFont ( fontFamily ) ;
106
+ if ( ! font ) {
107
+ console . warn (
108
+ `Font family "${ fontFamily } " not found, please load it first, using the default`
109
+ ) ;
110
+ font = getFont ( ) ;
111
+ }
92
112
const writtenText = font . getPath ( text , - startX , - startY , fontSize ) ;
93
113
const blueprints = Array . from ( sketchFontCommands ( writtenText . commands ) ) ;
94
114
return organiseBlueprints ( blueprints ) . mirror ( [ 0 , 0 ] ) ;
0 commit comments