-
Notifications
You must be signed in to change notification settings - Fork 0
/
typedraw.js
executable file
·82 lines (65 loc) · 2.05 KB
/
typedraw.js
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
#!/usr/bin/env node
const canvas = require('canvas');
const fs = require('fs');
function draw(file, typemap, text) {
const lines = text.split(/\r?\n/);
const x = 2;
const y = 36;
const spacing = 10.8;
const leading = 36;
const offset_y = -19;
const offset_x = 3;
const size = 27;
let max_length = 0;
lines.forEach((line) => {
max_length = Math.max(max_length, line.length);
});
const cvs = new canvas(x + (max_length + 3) * spacing, y + lines.length * leading);
const ctx = cvs.getContext('2d');
ctx._setFont('500', 'normal', 18, 'px', 'Fira Code');
lines.forEach((line, line_index) => {
Object.entries(typemap).forEach(([k, v]) => {
const re = new RegExp('\\b' + k + '\\b', 'g');
while ((match = re.exec(line)) != null) {
v.forEach(([type, color, nx, ny, nw, nh ]) => {
ctx.fillStyle = color;
switch (type) {
case 'rect':
ctx.fillRect(
nx * size + x + match.index * spacing - ((3 - k.length) / 2 * spacing) + offset_x,
ny * size + y + line_index * leading + offset_y,
nw * size,
nh * size
);
break;
case 'circle':
ctx.beginPath();
r = nw;
ctx.arc(
nx * k.length * spacing + x + match.index * spacing,
ny * size + y + line_index * leading - leading / 2 - 1,
r * size,
0,
2 * Math.PI
);
ctx.fill();
break;
}
});
}
line = line.replace(re, ' '.repeat(k.length));
});
ctx.fillStyle = '#333';
ctx.fillText(line, x, y + line_index * leading);
});
fs.writeFileSync(file, cvs.toBuffer());
}
if (process.argv.length < 3) {
console.log('Usage: typedraw <typemap.json> <out.png>');
}
else {
const typemap = JSON.parse(fs.readFileSync(process.argv[2], 'utf-8'));
const data = fs.readFileSync('/dev/stdin').toString();
console.log('Writing to', process.argv[3]);
draw(process.argv[3], typemap, data);
}