-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapplyCFF.ts
More file actions
240 lines (232 loc) · 8.27 KB
/
applyCFF.ts
File metadata and controls
240 lines (232 loc) · 8.27 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
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
import commands from "./commands.js";
type angleMode = 'rad' | 'deg' | 'turn';
export type style = {
fillStyle: string | CanvasGradient | CanvasPattern;
strokeStyle: string | CanvasGradient | CanvasPattern;
lineWidth: number;
lineCap: CanvasLineCap;
lineJoin: CanvasLineJoin;
miterLimit: number;
lineDash: number[];
lineDashOffset: number;
shadow: {
blur: number;
color: string;
offset: [number, number];
}
}
export const baseStyle: style = {
fillStyle: "black",
strokeStyle: "black",
lineWidth: 1,
lineCap: "butt",
lineJoin: "miter",
miterLimit: 10,
lineDash: [],
lineDashOffset: 0,
shadow: {
blur: 0,
color: "transparent",
offset: [0, 0],
}
}
export function processFile(file: string) {
const lines = file.split('\n').map(v => v.split('//')[0].trim().split(' '))
for (let i = 0; i < lines.length; i++) {
const commandText = lines[i];
/** Word combinations treated as one command */
const doubles: [string, string][] = [['dash', 'offset'], ['reset', 'transformations'], ['font', 'caps'], ['font', 'kerning'], ['font', 'stretch']]
/** Commands that will combine with the next word */
const wordFilters = ['fill', 'stroke', 'line', 'begin', 'close', 'miter', 'round', 'clear', 'move', 'shadow', 'clip', 'text', 'multi'];
if (commandText[0] == 'dash') console.log(commandText, wordFilters.includes(commandText[0]), doubles.findIndex(v=>v[0] == commandText[0] && v[1] == commandText[1]) != -1);
if (wordFilters.includes(commandText[0]) && commandText.length > 1 || doubles.findIndex(v => v[0] == commandText[0] && v[1] == commandText[1]) != -1) commandText[0] = `${commandText.shift()} ${commandText[0]}`;
// Skip lines, returns, etc.
if (!commandText.length || !commandText[0].length) {
lines.splice(i, 1);
i--;
continue; // Skip empty lines
}
if (commandText[0] == 'skip' && commandText[2] == 'line') {
let value = parseFloat(commandText[4].trim());
if (value > i) i = value;
}
if (commandText[0] == 'return') {
lines.splice(i);
break;
}
lines[i] = commandText;
}
return lines
}
function applyStyles(
ctx: canvasContext,
scale: number,
style: style = baseStyle
) {
ctx.fillStyle = style.fillStyle;
ctx.lineWidth = style.lineWidth * scale;
ctx.strokeStyle = style.strokeStyle;
ctx.lineCap = style.lineCap;
ctx.lineJoin = style.lineJoin;
ctx.miterLimit = style.miterLimit * scale;
ctx.setLineDash(style.lineDash.map(v => v * scale));
ctx.lineDashOffset = style.lineDashOffset * scale;
ctx.shadowBlur = style.shadow.blur;
ctx.shadowColor = style.shadow.color;
ctx.shadowOffsetX = style.shadow.offset[0];
ctx.shadowOffsetY = style.shadow.offset[1];
}
function toRadians(value: number, mode: angleMode): number {
if (mode === 'deg') {
return (value * Math.PI) / 180;
}
if (mode === 'turn') {
return value * 2 * Math.PI;
}
else return value
}
type canvasContext = CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D
function pathMode(path: string[][], scale: number): Path2D {
let path2d = new Path2D();
for (let i = 0; i < path.length; i++) {
const content = path[i];
let command = content[0];
const contents = content.slice(1).map((v) => parseFloat(v) * scale);
if (!isNaN(parseFloat(command))) {
contents.unshift(parseFloat(command) * scale);
command = 'line';
}
if (command == 'skip' || command == 'move') path2d.moveTo(contents[0], contents[1]);
else if (command == 'line') path2d.lineTo(contents[0], contents[1]);
else if (command == 'bezier') path2d.bezierCurveTo(contents[0], contents[1], contents[2], contents[3], contents[4], contents[5]);
else if (command == 'quadratic') path2d.quadraticCurveTo(contents[0], contents[1], contents[2], contents[3]);
else if (command == 'arc') path2d.arc(contents[0], contents[1], contents[2], contents[3], contents[4], content[6] == 'true');
else if (command == 'arcTo') path2d.arcTo(contents[0], contents[1], contents[2], contents[3], contents[4]);
else if (command == 'ellipse') path2d.ellipse(contents[0], contents[1], contents[2], contents[3], contents[4], contents[5], contents[6], content[8] == 'true');
else if (command == 'rect') path2d.rect(contents[0], contents[1], contents[2], contents[3]);
else if (command == 'round' && content[1] == 'rect') path2d.roundRect(contents[1], contents[2], contents[3], contents[4], contents[5]);
else if (command == 'close') path2d.closePath();
else console.log(`Path command error ${command}\n${path.join('\n')}`)
}
return path2d;
}
function saveContext(ctx: canvasContext, scale: number): style {
return {
fillStyle: ctx.fillStyle,
strokeStyle: ctx.strokeStyle,
lineWidth: ctx.lineWidth / scale,
lineCap: ctx.lineCap,
lineJoin: ctx.lineJoin,
miterLimit: ctx.miterLimit / scale,
lineDash: ctx.getLineDash().map(v => v / scale),
lineDashOffset: ctx.lineDashOffset / scale,
shadow: {
blur: ctx.shadowBlur,
color: ctx.shadowColor,
offset: [ctx.shadowOffsetX, ctx.shadowOffsetY]
}
}
}
/**
* Apply a canvas file to a canvas context
* @param ctx The canvas context to apply the file to
* @param file The file to apply
* @param scale The scale to apply to the file
*/
export default function applyCFF(
ctx: canvasContext,
file: string,
scale: number = 1
) {
if (ctx) {
applyStyles(
ctx,
scale
);
let groups: style[] = [];
let angleMode: angleMode = "deg"; // Degrees are nicer to type
const lines = processFile(file);
for (let i = 0; i < lines.length; i++) {
const commandText = lines[i];
// Groups and Paths
if (commandText[0] == 'group') {
groups.push(saveContext(ctx, scale)); // Start of a group block
ctx.save(); // Save the current state
ctx.beginPath(); // Start a new path
continue;
}
if (commandText[0] == 'fill path') {
let index = lines.findIndex((v, j)=>v[0] == '}' && j > i);
ctx.fill(pathMode(lines.slice(i + 1, index), scale));
i = index;
continue;
} else if (commandText[0] == 'stroke path') {
let index = lines.findIndex((v, j) => v[0] == '}' && j > i);
ctx.stroke(pathMode(lines.slice(i + 1, index), scale));
i = index;
continue;
} else if (commandText[0] == 'multi path') {
let index = lines.findIndex((v, j) => v[0] == '}' && j > i);
const path = pathMode(lines.slice(i + 1, index), scale);
ctx.fill(path);
ctx.stroke(path);
i = index;
continue;
} else if (commandText[0] == 'clip path') {
let index = lines.findIndex((v, j) => v[0] == '}' && j > i);
ctx.clip(pathMode(lines.slice(i + 1, index), scale));
i = index;
continue;
} else if (commandText[0] == '}') {
ctx.restore(); // Restore the previous state
applyStyles(ctx, scale, groups.pop());
ctx.beginPath(); // Start a new path
continue;
}
if (commandText[0] == 'return')
break;
// Angle Modes
if (commandText[0] == 'use') {
if (commandText[1] == 'radians' || commandText[1] == 'rad') {
angleMode = 'rad';
continue;
} else if (commandText[1] == 'degrees' || commandText[1] == 'deg') {
angleMode = 'deg';
continue;
} else if (commandText[1] == 'turns' || commandText[1] == 'turn') {
angleMode = 'turn';
continue;
}
}
const command = commands[commandText[0] as keyof typeof commands];
if (command) {
if (command.availability == 'basic' || command.availability == 'applyStyles') {
// Valid Command for enviroment
let args: any[] = [];
commandText.slice(1).forEach((arg, i, arr) => {
if (command.args[i] == 'text') {
args.push(arg);
} else if (command.args[i] == 'number') {
args.push(parseFloat(arg));
} else if (command.args[i] == 'boolean') {
args.push(arg == 'true');
} else if (command.args[i] == 'point') {
args.push(parseFloat(arg) * scale);
} else if (command.args[i] == 'angle') {
let angle = arg == 'PI' ? Math.PI : arg.includes('PI') ? parseInt(arg.replace('PI', '')) * Math.PI : parseFloat(arg);
args.push(toRadians(angle, angleMode));
} else if (command.args[i] == 'pointArray') {
args.push(arr.slice(i).map((a) => parseFloat(a) * scale));
} else if (command.args[i] == 'textArray') {
args.push(arr.slice(i));
}
})
command.handler(ctx, args as any);
if (command.availability == 'applyStyles') applyStyles(ctx, scale);
}
} else {
console.error(`Command ${commandText[0]} in line ${i} not found "${commandText.join(' ')}"`)
}
}
}
}