-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
107 lines (83 loc) · 2.46 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
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
import express, { Request, Response } from "express";
import { Canvas, createCanvas } from "canvas";
import dotenv from "dotenv";
import { HELLOS, Language } from "./hellos";
import { registerFonts } from "./fonts";
dotenv.config();
const CUSTOM_FONT_LANGUAGES: Language[] = ["Japanese", "Korean", "Chinese"];
const app = express();
const port = process.env.PORT || 3000;
registerFonts();
function getRandomLanguage() {
const languages = Object.keys(HELLOS);
return languages[
Math.floor(Math.random() * Object.keys(HELLOS).length)
] as Language;
}
function getFontForLanguage(language: Language) {
return CUSTOM_FONT_LANGUAGES.includes(language)
? `Noto Sans ${language}`
: "Noto Sans";
}
function parseBorderRadius(borderRadius: string | number) {
if (typeof borderRadius == "number") return borderRadius;
if (borderRadius.includes(",")) {
return borderRadius.split(",").map((r) => Number(r));
}
return Number(borderRadius) || 20;
}
type DrawOptions = {
width?: number | string;
height?: number | string;
fontSize?: number | string;
textColor?: string;
bgColor?: string;
borderRadius?: number | string;
};
function drawHello({
width = 300,
height = 200,
fontSize = 40,
textColor = "white",
bgColor = "teal",
borderRadius = 20,
}: DrawOptions): Canvas {
width = Number(width) || 300;
height = Number(height) || 200;
fontSize = Number(fontSize) || 40;
const parsedBorderRadius = parseBorderRadius(borderRadius);
const canvas = createCanvas(width, height);
const ctx = canvas.getContext("2d");
const language = getRandomLanguage();
ctx.fillStyle = bgColor || "teal";
ctx.roundRect(0, 0, width, height, parsedBorderRadius);
ctx.fill();
const font = getFontForLanguage(language);
ctx.font = `${fontSize}px "${font}"`;
ctx.fillStyle = textColor;
const text = HELLOS[language];
const textSize = ctx.measureText(text);
ctx.fillText(
text,
width / 2 - textSize.width / 2,
height / 2 + textSize.actualBoundingBoxAscent / 2
);
return canvas;
}
app.get<"/", {}, {}, {}, DrawOptions>(
"/",
(req: Request<{}, {}, {}, DrawOptions>, res: Response) => {
try {
const canvas = drawHello(req.query);
res.contentType("image/png");
res.send(canvas.toBuffer("image/png"));
} catch (e) {
console.error(e);
res.status(400).send("Bad request");
}
}
);
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
export default app;