-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
35 lines (34 loc) · 1.01 KB
/
index.ts
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
import { createCanvas } from 'canvas';
import { layout } from './libs/layout';
import { parse } from './libs/parse';
import { draw } from './draw';
export type PosterParamsType = {
jsx: string;
props?: Record<string, any>;
mimeType?: 'image/jpeg' | 'image/png';
returnType: 'buffer' | 'base64';
};
export default async function poster({
jsx,
props,
mimeType = 'image/jpeg',
returnType = 'buffer',
}: PosterParamsType) {
const root = parse(jsx, props);
const element = layout(root);
const { width, height } = element.node?.getComputedLayout() || {};
const canvas = createCanvas(width || 0, height || 0);
const ctx = canvas.getContext('2d');
await draw(ctx, root);
if (mimeType === 'image/png') {
if (returnType === 'base64') {
return canvas.toDataURL('image/png');
}
return canvas.toBuffer('image/png');
} else {
if (returnType === 'base64') {
return canvas.toDataURL('image/jpeg');
}
return canvas.toBuffer('image/jpeg');
}
}