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
// prototype color contrast swatch
/** @jsxImportSource https://esm.sh/preact */
import chroma from "npm:chroma-js";
import { render } from "npm:preact-render-to-string";
export default async function(req: Request): Promise<Response> {
const params = new URL(req.url).searchParams;
const color = params.get("color") || "ff6347";
const bg = "#" + color;
let fg = "#fff";
try {
const rgb = chroma(bg).rgb();
const neg = rgb.map(n => 255 - n);
fg = chroma(neg).hex();
} catch (e) {
console.error(e);
}
const contrast = chroma.contrast(bg, fg);
const svg = render(
<svg
xmlns="http://www.w3.org/2000/svg"
width="256"
height="256"
viewBox="0 0 256 256"
fill={fg}
style={{
fontFamily: "system-ui, sans-serif",
fontWeight: 700,
fontSize: 64,
}}
>
<rect
width="256"
height="256"
fill={bg}
/>
<text
textAnchor="middle"
x="128"
y="128"
dominantBaseline="middle"
>
{contrast.toFixed(2)}
</text>
</svg>,
);
return new Response(svg, { headers: { "Content-Type": "image/svg+xml;charset=utf-8" } });
}