-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathImageFont.ts
87 lines (74 loc) · 2.61 KB
/
ImageFont.ts
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
83
84
85
86
87
import Screen from './Screen';
import Font from './Font';
import Image from './Image';
import SceneObject from './SceneObject';
import LocalFileLoader from './LocalFileLoader';
export default class ImageFont extends Font {
public onGetWidth: ((ch: string, fontWidth: number) => number) | null = null;
private image: Image;
private fontWidth: number;
private fontHeight: number;
private columns: number = -1;
private map: Map<string, number> = new Map<string, number>();
private offscreenElement: HTMLCanvasElement;
private offscreen: CanvasRenderingContext2D | null = null;
constructor(imgFilename: string, charListFilename: string, fontWidth: number, fontHeight: number) {
super();
this.image = new Image(imgFilename);
this.fontWidth = fontWidth;
this.fontHeight = fontHeight;
this.offscreenElement = document.createElement('canvas');
this.offscreenElement.width = this.fontWidth;
this.offscreenElement.height = this.fontHeight;
this.offscreen = this.offscreenElement.getContext('2d');
const loader = new LocalFileLoader();
loader.loadAsText(charListFilename, (data: string | null): any => {
if (data) {
for (let i = 0; i < data.length; i++) {
if (this.map.get(data[i]) === undefined) {
this.map.set(data[i], i);
}
}
}
});
}
public getWidth = (ch: string): number => {
if (this.onGetWidth) {
return this.onGetWidth(ch, this.fontWidth);
} else {
return this.fontWidth;
}
}
public getHeight = (): number => {
return this.fontHeight;
}
public drawGlyph = (
sender: SceneObject,
screen: Screen,
x: number,
y: number,
fontColor: string,
ch: string): void => {
const index = this.map.get(ch);
if (index === undefined) {
return;
}
/**
* On constructor this.columns cannot be calculated.
* So, the member varaible should be assigned when available.
*/
if (this.columns < 0) {
this.columns = Math.floor(this.image.getWidth() / this.fontWidth);
}
if (index !== undefined) {
screen.drawImage(
sender,
this.image,
(index % this.columns) * this.fontWidth,
Math.floor(index / this.columns) * this.fontHeight,
this.fontWidth,
this.fontHeight,
x, y);
}
}
}