1
1
import getImageSize from "image-size" ;
2
+ import { createCanvas } from "canvas" ;
2
3
3
4
type IGetTextWidth = (
4
5
inputText : string | number | null ,
5
6
options : {
6
7
fontSize : number ;
7
- ratio ?: number ;
8
+ fontFamily ?: string ;
9
+ fontWeight ?: string ;
8
10
}
9
11
) => number ;
10
12
11
13
export const getTextWidth : IGetTextWidth = ( inputText , options ) => {
12
- const { fontSize = 16 , ratio = 0.5 } = options ;
14
+ const {
15
+ fontSize = 16 ,
16
+ fontFamily = "sans-serif" ,
17
+ fontWeight = "normal" ,
18
+ } = options ;
13
19
14
- let width = 0 ;
15
20
let text = inputText ?? "" ;
16
21
text = text . toString ( ) ;
17
22
18
- // Estimate the width using a monospace font (each character has the same width)
19
- width = text . length * fontSize * ratio ;
20
- return width ;
23
+ const canvas = createCanvas ( 0 , 0 ) ;
24
+ const context = canvas . getContext ( "2d" ) ;
25
+ context . font = `${ fontWeight } ${ fontSize } px ${ fontFamily } ` ;
26
+
27
+ const metrics = context . measureText ( text ) ;
28
+ return metrics . width ;
21
29
} ;
22
30
23
31
type IWrapText = (
24
32
inputText : string ,
25
33
options : {
26
34
maxLineWidth : number ;
27
- fontSize : number ;
28
35
maxLines ?: number ;
36
+ fontSize : number ;
37
+ fontWeight ?: string ;
29
38
} ,
30
39
cb : ( value : string , index : number , array : Array < string > ) => JSX . Element
31
40
) => Array < JSX . Element > ;
@@ -40,7 +49,10 @@ export const wrapText: IWrapText = (inputText, options, cb) => {
40
49
for ( let i = 1 ; i < words . length ; i ++ ) {
41
50
const word = words [ i ] ;
42
51
const testLine = currentLine + " " + word ;
43
- const testWidth = getTextWidth ( testLine , { fontSize : options . fontSize } ) ;
52
+ const testWidth = getTextWidth ( testLine , {
53
+ fontSize : options . fontSize ,
54
+ fontWeight : options . fontWeight ,
55
+ } ) ;
44
56
45
57
if ( testWidth > maxLineWidth ) {
46
58
lines . push ( currentLine ) ;
@@ -83,6 +95,10 @@ export const convertDateToReadableFormat: IConvertDateToReadbleFormat = (
83
95
return `${ month } ${ day } '${ year } ` ;
84
96
} ;
85
97
98
+ export function rgbToHex ( [ r , g , b ] : Array < number > ) {
99
+ return "#" + [ r , g , b ] . map ( ( x ) => x . toString ( 16 ) . padStart ( 2 , "0" ) ) . join ( "" ) ;
100
+ }
101
+
86
102
export function hexToRgb ( hex : string , alpha = 1 ) {
87
103
const bigint = parseInt ( hex . slice ( 1 ) , 16 ) ;
88
104
const r = ( bigint >> 16 ) & 255 ;
0 commit comments