-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
45 lines (36 loc) · 1.6 KB
/
index.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
const DEFAULT_CHAR_HEIGHT = 5;
const DEFAULT_COLOR = '#000';
export const initFont = ({ height=DEFAULT_CHAR_HEIGHT, ...chars }={}, ctx) => {
if (!chars) {
console.error('No font provided!');
return
}
if (!ctx) {
console.error('No context provided');
return
}
const bin2arr = (bin, width) => bin.match(new RegExp(`.{${width}}`, 'g'));
const isNumber = code => code > 0;
return (string, x=0, y=0, size=24, color=DEFAULT_COLOR) => {
const renderChar = (charX, char) => {
const pixelSize = size/height;
const fontCode = chars[char.charCodeAt()] || '';
const binaryChar = isNumber(fontCode) ? fontCode : fontCode.codePointAt();
const binary = (binaryChar || 0).toString(2);
const width = Math.ceil(binary.length / height);
const marginX = charX + pixelSize;
const formattedBinary = binary.padStart(width * height, 0);
const binaryCols = bin2arr(formattedBinary, height);
console.debug('Rendering char', char, char.charCodeAt(), fontCode, binaryChar, binaryCols);
binaryCols.map((column, colPos) =>
[...column].map((pixel, pixPos) => {
ctx.fillStyle = !+pixel ? 'transparent' : color; // pixel == 0 ?
ctx.fillRect(x + marginX + colPos * pixelSize, y + pixPos * pixelSize, pixelSize, pixelSize);
})
);
return charX + (width+1)*pixelSize
};
console.debug('Rendering string', string);
[...string].reduce(renderChar, 0);
};
};