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
/** @jsxImportSource https://esm.sh/preact */
import { Color } from "https://deno.land/x/color/mod.ts";
import { render } from "https://deno.land/x/resvg_wasm/mod.ts";
import { render as preact } from "npm:preact-render-to-string";
const HEXRE = /^[A-Fa-f0-9]{3,6}$/;
const toHex = str => HEXRE.test(str) ? "#" + str : str;
export default async function(req: Request): Promise<Response> {
const url = new URL(req.url);
const [a, b] = url.pathname.split("/").slice(1);
const size = 256;
const fontSize = 64;
const color = !!a ? toHex(a) : "#fff";
const bg = !!b ? toHex(b) : "#000";
const data = {
color: Color.string(color),
bg: Color.string(bg),
};
data.contrast = data.color.contrast(data.bg);
const text = data.contrast.toFixed(2);
const svg = preact(
<svg
xmlns="http://www.w3.org/2000/svg"
width={size}
height={size}
viewBox={`0 0 ${size} ${size}`}
fill={color}
style={{
fontFamily: "sans-serif",
fontWeight: "bold",
fontSize,
}}
>
<rect
x="0"
y="0"
width={size}
height={size}
fill={bg}
/>
<text
x="50%"
y={size / 2 + fontSize * 0.25}
textAnchor="middle"
dominantBaseline="middle"
>
{text}
</text>
</svg>,
);
const png = await render(svg);
return new Response(png, {
headers: {
"Content-Type": "image/png",
},
});
}