-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgenerateImage.js
More file actions
55 lines (44 loc) · 1.26 KB
/
Copy pathgenerateImage.js
File metadata and controls
55 lines (44 loc) · 1.26 KB
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
import { createCanvas, loadImage } from "canvas";
export async function generateImage(contributors) {
const AVATAR_SIZE = 50;
const GAP = 4;
const COLS = 40;
const ROWS = Math.ceil(contributors.length / COLS);
const width = COLS * AVATAR_SIZE + (COLS - 1) * GAP;
const height = ROWS * AVATAR_SIZE + (ROWS - 1) * GAP;
const canvas = createCanvas(width, height);
const ctx = canvas.getContext("2d");
for (let i = 0; i < contributors.length; i++) {
const c = contributors[i];
const col = i % COLS;
const row = Math.floor(i / COLS);
const x = col * (AVATAR_SIZE + GAP);
const y = row * (AVATAR_SIZE + GAP);
const img = await loadAvatar(c.avatar_url);
ctx.save();
ctx.beginPath();
ctx.arc(
x + AVATAR_SIZE / 2,
y + AVATAR_SIZE / 2,
AVATAR_SIZE / 2,
0,
Math.PI * 2,
);
ctx.clip();
if (img) {
ctx.drawImage(img, x, y, AVATAR_SIZE, AVATAR_SIZE);
}
ctx.restore();
}
return canvas.toBuffer("image/png");
}
async function loadAvatar(url) {
try {
const res = await fetch(url);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const buffer = Buffer.from(await res.arrayBuffer());
return await loadImage(buffer);
} catch (err) {
return null;
}
}