Public
HTTP (deprecated)
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
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
// svg-based pie chart service
/* usage:
* https://jxnblk-pie.web.val.run/?values=4,5,6
*/
/** @jsxImportSource https://esm.sh/preact */
import chroma from "npm:chroma-js";
import { render } from "npm:preact-render-to-string";
const R = 128;
const dashArray = n => `${(R * Math.PI * n)} ${Math.PI * R}`;
export default async function(req: Request): Promise<Response> {
const params = new URL(req.url).searchParams;
const { values, ...args } = Object.fromEntries(params);
const arr = values !== undefined ? values.split(",").map(Number) : undefined;
let segments = [];
if (arr != undefined) {
const total = arr.reduce((n, a) => a + n, 0);
const colors = chroma.scale(chroma.brewer.GnBu).domain([0, arr.length - 1]);
arr.forEach((n, i) => {
const value = n / total;
const start = i === 0 ? 0 : segments[i - 1].end;
const end = start + value * 360;
segments.push({
index: 1,
value,
start,
end,
color: colors(i).hex(),
});
});
}
const svg = render(
<svg
xmlns="http://www.w3.org/2000/svg"
width="256"
height="256"
viewBox="0 0 256 256"
fill="#fff"
>
<circle cx="128" cy="128" r="128" fill="#333" />
{segments.map((s, i) => (
<circle
key={s.value + i}
cx="128"
cy="128"
r="64"
fill="none"
stroke={s.color}
strokeWidth="128"
strokeDasharray={dashArray(s.value)}
transform={`rotate(${-90 + s.start} 128 128)`}
/>
))}
</svg>,
);
// DEBUG // return new Response(JSON.stringify(segments, null, 2), { headers: { "Content-Type": "text/plain" } });
return new Response(svg, { headers: { "Content-Type": "image/svg+xml;charset=utf-8" } });
}
jxnblk-pie.web.val.run
May 17, 2024