-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
52 lines (45 loc) · 1.84 KB
/
index.js
File metadata and controls
52 lines (45 loc) · 1.84 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
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
}
return ( string, x = 0, y = 0, size = 24, color = DEFAULT_COLOR ) => {
const pixelSize = size / height;
const renderChar = ( charX, char ) => {
const fontCode = chars[ char.charCodeAt() ] || '';
let bin = Number.isInteger( fontCode ) ? fontCode : fontCode.codePointAt();
const binary = ( bin || 0 ).toString( 2 );
const width = Math.ceil( binary.length / height );
const mask = ( 1 << height ) - 1;
ctx.fillStyle = color;
for ( let col = width; col > 0; col-- ) {
let rowPos = height - 1;
for ( let row = bin & mask; row > 0; row >>= 1 ) {
if ( row & 1 ) {
let y1 = y + rowPos * pixelSize, h = pixelSize;
// This while loop greatly reduces the amount of draw calls.
// If you need a few more bytes, you could remove this.
while ( ( row >> 1 ) & 1 ) {
y1 -= pixelSize;
h += pixelSize;
row >>= 1;
rowPos--;
}
ctx.fillRect( x + charX + col * pixelSize, y1, pixelSize, h );
}
rowPos--;
}
bin >>= height;
}
return charX + ( width + 1 ) * pixelSize;
};
console.debug('Rendering string', string);
[...string].reduce(renderChar, 0);
};
};