-
Notifications
You must be signed in to change notification settings - Fork 480
/
glyph.mjs
535 lines (465 loc) · 18.2 KB
/
glyph.mjs
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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
// The Glyph object
import check from './check.mjs';
import draw from './draw.mjs';
import Path from './path.mjs';
import { getPaletteColor, formatColor } from './tables/cpal.mjs';
// import glyf from './tables/glyf' Can't be imported here, because it's a circular dependency
function getPathDefinition(glyph, path) {
let _path = path || new Path();
return {
configurable: true,
get: function() {
if (typeof _path === 'function') {
_path = _path();
}
return _path;
},
set: function(p) {
_path = p;
}
};
}
/**
* @typedef GlyphOptions
* @type Object
* @property {string} [name] - The glyph name
* @property {number} [unicode]
* @property {Array} [unicodes]
* @property {number} [xMin]
* @property {number} [yMin]
* @property {number} [xMax]
* @property {number} [yMax]
* @property {number} [advanceWidth]
* @property {number} [leftSideBearing]
*/
// A Glyph is an individual mark that often corresponds to a character.
// Some glyphs, such as ligatures, are a combination of many characters.
// Glyphs are the basic building blocks of a font.
//
// The `Glyph` class contains utility methods for drawing the path and its points.
/**
* @exports opentype.Glyph
* @class
* @param {GlyphOptions}
* @constructor
*/
function Glyph(options) {
// By putting all the code on a prototype function (which is only declared once)
// we reduce the memory requirements for larger fonts by some 2%
this.bindConstructorValues(options);
}
/**
* @param {GlyphOptions}
*/
Glyph.prototype.bindConstructorValues = function(options) {
this.index = options.index || 0;
if (options.name === '.notdef') {
options.unicode = undefined;
} else if (options.name === '.null') {
options.unicode = 0;
}
if (options.unicode === 0 && options.name !== '.null') {
throw new Error('The unicode value "0" is reserved for the glyph name ".null" and cannot be used by any other glyph.');
}
// These three values cannot be deferred for memory optimization:
this.name = options.name || null;
this.unicode = options.unicode;
this.unicodes = options.unicodes || (options.unicode !== undefined ? [options.unicode] : []);
// But by binding these values only when necessary, we reduce can
// the memory requirements by almost 3% for larger fonts.
if ('xMin' in options) {
this.xMin = options.xMin;
}
if ('yMin' in options) {
this.yMin = options.yMin;
}
if ('xMax' in options) {
this.xMax = options.xMax;
}
if ('yMax' in options) {
this.yMax = options.yMax;
}
if ('advanceWidth' in options) {
this.advanceWidth = options.advanceWidth;
}
if ('leftSideBearing' in options) {
this.leftSideBearing = options.leftSideBearing;
}
if ('points' in options) {
this.points = options.points;
}
// The path for a glyph is the most memory intensive, and is bound as a value
// with a getter/setter to ensure we actually do path parsing only once the
// path is actually needed by anything.
Object.defineProperty(this, 'path', getPathDefinition(this, options.path));
};
/**
* @param {number}
*/
Glyph.prototype.addUnicode = function(unicode) {
if (this.unicodes.length === 0) {
this.unicode = unicode;
}
this.unicodes.push(unicode);
};
/**
* Calculate the minimum bounding box for this glyph.
* @return {opentype.BoundingBox}
*/
Glyph.prototype.getBoundingBox = function() {
return this.path.getBoundingBox();
};
/**
* Convert the glyph to a Path we can draw on a drawing context.
* @param {number} [x=0] - Horizontal position of the beginning of the text.
* @param {number} [y=0] - Vertical position of the *baseline* of the text.
* @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`.
* @param {GlyphRenderOptions=} options - xScale, yScale to stretch the glyph.
* @param {opentype.Font} font if hinting is to be used, or CPAL/COLR / variation needs to be rendered, the font
* @return {opentype.Path}
*/
Glyph.prototype.getPath = function(x, y, fontSize, options, font) {
x = x !== undefined ? x : 0;
y = y !== undefined ? y : 0;
fontSize = fontSize !== undefined ? fontSize : 72;
options = Object.assign({}, font && font.defaultRenderOptions, options);
let commands;
let hPoints;
let xScale = options.xScale;
let yScale = options.yScale;
const scale = 1 / (this.path.unitsPerEm || 1000) * fontSize;
let useGlyph = this;
if(font && font.variation) {
useGlyph = font.variation.getTransform(this, options.variation);
commands = useGlyph.path.commands;
}
if (options.hinting && font && font.hinting) {
// in case of hinting, the hinting engine takes care
// of scaling the points (not the path) before hinting.
hPoints = useGlyph.path && font.hinting.exec(useGlyph, fontSize, options);
// in case the hinting engine failed hPoints is undefined
// and thus reverts to plain rending
}
if (hPoints) {
// Call font.hinting.getCommands instead of `glyf.getPath(hPoints).commands` to avoid a circular dependency
commands = font.hinting.getCommands(hPoints);
x = Math.round(x);
y = Math.round(y);
// TODO in case of hinting xyScaling is not yet supported
xScale = yScale = 1;
} else {
commands = useGlyph.path.commands;
if (xScale === undefined) xScale = scale;
if (yScale === undefined) yScale = scale;
}
const p = new Path();
if ( options.drawSVG ) {
const svgImage = this.getSvgImage(font);
if ( svgImage ) {
const layer = new Path();
layer._image = {
image: svgImage.image,
x: x + svgImage.leftSideBearing * scale,
y: y - svgImage.baseline * scale,
width: svgImage.image.width * scale,
height: svgImage.image.height * scale,
};
p._layers = [layer];
return p;
}
}
if ( options.drawLayers ) {
const layers = this.getLayers(font);
if ( layers && layers.length ) {
p._layers = [];
for ( let i = 0; i < layers.length; i += 1 ) {
const layer = layers[i];
let color = getPaletteColor(font, layer.paletteIndex, options.usePalette);
if ( color === 'currentColor' ) {
color = options.fill || 'black';
} else {
color = formatColor(color, options.colorFormat || 'rgba');
}
options = Object.assign({}, options, {fill: color});
p._layers.push(this.getPath.call(layer.glyph, x, y, fontSize, options, font));
}
return p;
}
}
p.fill = options.fill || this.path.fill;
p.stroke = this.path.stroke;
p.strokeWidth = this.path.strokeWidth * scale;
for (let i = 0; i < commands.length; i += 1) {
const cmd = commands[i];
if (cmd.type === 'M') {
p.moveTo(x + (cmd.x * xScale), y + (-cmd.y * yScale));
} else if (cmd.type === 'L') {
p.lineTo(x + (cmd.x * xScale), y + (-cmd.y * yScale));
} else if (cmd.type === 'Q') {
p.quadraticCurveTo(x + (cmd.x1 * xScale), y + (-cmd.y1 * yScale),
x + (cmd.x * xScale), y + (-cmd.y * yScale));
} else if (cmd.type === 'C') {
p.curveTo(x + (cmd.x1 * xScale), y + (-cmd.y1 * yScale),
x + (cmd.x2 * xScale), y + (-cmd.y2 * yScale),
x + (cmd.x * xScale), y + (-cmd.y * yScale));
} else if (cmd.type === 'Z' && p.stroke && p.strokeWidth) {
p.closePath();
}
}
return p;
};
/**
*
* @param {opentype.Font} font
* @returns {Array}
*/
Glyph.prototype.getLayers = function(font) {
if(!font) {
throw Error('The font object is required to read the colr/cpal tables in order to get the layers.');
}
return font.layers.get(this.index);
};
/**
* @param {opentype.Font} font
* @returns {import('./svgimages.mjs').SVGImage | undefined}
*/
Glyph.prototype.getSvgImage = function(font) {
if(!font) {
throw Error('The font object is required to read the svg table in order to get the image.');
}
return font.svgImages.get(this.index);
};
/**
* Split the glyph into contours.
* This function is here for backwards compatibility, and to
* provide raw access to the TrueType glyph outlines.
* @param {Array|null} [transformedPoints=null] Use the supplied transformed points from a glyph variation instead of the regular glyph points
* @return {Array}
*/
Glyph.prototype.getContours = function(transformedPoints = null) {
if (this.points === undefined && !transformedPoints) {
return [];
}
const contours = [];
let currentContour = [];
let points = transformedPoints ? transformedPoints : this.points;
for (let i = 0; i < points.length; i += 1) {
const pt = points[i];
currentContour.push(pt);
if (pt.lastPointOfContour) {
contours.push(currentContour);
currentContour = [];
}
}
check.argument(currentContour.length === 0, 'There are still points left in the current contour.');
return contours;
};
/**
* Calculate the xMin/yMin/xMax/yMax/lsb/rsb for a Glyph.
* @return {Object}
*/
Glyph.prototype.getMetrics = function() {
const commands = this.path.commands;
const xCoords = [];
const yCoords = [];
for (let i = 0; i < commands.length; i += 1) {
const cmd = commands[i];
if (cmd.type !== 'Z') {
xCoords.push(cmd.x);
yCoords.push(cmd.y);
}
if (cmd.type === 'Q' || cmd.type === 'C') {
xCoords.push(cmd.x1);
yCoords.push(cmd.y1);
}
if (cmd.type === 'C') {
xCoords.push(cmd.x2);
yCoords.push(cmd.y2);
}
}
const metrics = {
xMin: Math.min.apply(null, xCoords),
yMin: Math.min.apply(null, yCoords),
xMax: Math.max.apply(null, xCoords),
yMax: Math.max.apply(null, yCoords),
leftSideBearing: this.leftSideBearing
};
if (!isFinite(metrics.xMin)) {
metrics.xMin = 0;
}
if (!isFinite(metrics.xMax)) {
metrics.xMax = this.advanceWidth;
}
if (!isFinite(metrics.yMin)) {
metrics.yMin = 0;
}
if (!isFinite(metrics.yMax)) {
metrics.yMax = 0;
}
metrics.rightSideBearing = this.advanceWidth - metrics.leftSideBearing - (metrics.xMax - metrics.xMin);
return metrics;
};
/**
* Draw the glyph on the given context.
* @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas.
* @param {number} [x=0] - Horizontal position of the beginning of the text.
* @param {number} [y=0] - Vertical position of the *baseline* of the text.
* @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`.
* @param {Object=} options - xScale, yScale to stretch the glyph.
* @param {opentype.Font} font - if hinting is to be used, or CPAL/COLR / variation needs to be rendered, the font
*/
Glyph.prototype.draw = function(ctx, x, y, fontSize, options, font) {
options = Object.assign({}, font && font.defaultRenderOptions, options);
const path = this.getPath(x, y, fontSize, options, font);
path.draw(ctx);
};
/**
* Draw the points of the glyph.
* On-curve points will be drawn in blue, off-curve points will be drawn in red.
* @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas.
* @param {number} [x=0] - Horizontal position of the beginning of the text.
* @param {number} [y=0] - Vertical position of the *baseline* of the text.
* @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`.
* @param {GlyphRenderOptions=} options
* @param {opentype.Font} font - used to get the default render options, may be needed for variable fonts in the future
*/
Glyph.prototype.drawPoints = function(ctx, x, y, fontSize, options, font) {
options = Object.assign({}, font && font.defaultRenderOptions, options);
if ( options.drawLayers ) {
const layers = this.getLayers(font);
if ( layers && layers.length ) {
for ( let l = 0; l < layers.length; l += 1 ) {
// prevent endless loop: ignore layers with own glyph id
if(layers[l].glyph.index !== this.index) {
this.drawPoints.call(layers[l].glyph, ctx, x, y, fontSize);
}
}
return;
}
}
function drawCircles(l, x, y, scale) {
ctx.beginPath();
for (let j = 0; j < l.length; j += 1) {
ctx.moveTo(x + (l[j].x * scale), y + (l[j].y * scale));
ctx.arc(x + (l[j].x * scale), y + (l[j].y * scale), 2, 0, Math.PI * 2, false);
}
ctx.fill();
}
x = x !== undefined ? x : 0;
y = y !== undefined ? y : 0;
fontSize = fontSize !== undefined ? fontSize : 24;
const scale = 1 / this.path.unitsPerEm * fontSize;
const blueCircles = [];
const redCircles = [];
const path = this.path;
let commands = path.commands;
if(font && font.variation) {
commands = font.variation.getTransform(this, options.variation).path.commands;
}
for (let i = 0; i < commands.length; i += 1) {
const cmd = commands[i];
if (cmd.x !== undefined) {
blueCircles.push({x: cmd.x, y: -cmd.y});
}
if (cmd.x1 !== undefined) {
redCircles.push({x: cmd.x1, y: -cmd.y1});
}
if (cmd.x2 !== undefined) {
redCircles.push({x: cmd.x2, y: -cmd.y2});
}
}
ctx.fillStyle = 'blue';
drawCircles(blueCircles, x, y, scale);
ctx.fillStyle = 'red';
drawCircles(redCircles, x, y, scale);
};
/**
* Draw lines indicating important font measurements.
* Black lines indicate the origin of the coordinate system (point 0,0).
* Blue lines indicate the glyph bounding box.
* Green line indicates the advance width of the glyph.
* @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas.
* @param {number} [x=0] - Horizontal position of the beginning of the text.
* @param {number} [y=0] - Vertical position of the *baseline* of the text.
* @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`.
*/
Glyph.prototype.drawMetrics = function(ctx, x, y, fontSize) {
let scale;
x = x !== undefined ? x : 0;
y = y !== undefined ? y : 0;
fontSize = fontSize !== undefined ? fontSize : 24;
scale = 1 / this.path.unitsPerEm * fontSize;
ctx.lineWidth = 1;
// Draw the origin
ctx.strokeStyle = 'black';
draw.line(ctx, x, -10000, x, 10000);
draw.line(ctx, -10000, y, 10000, y);
// This code is here due to memory optimization: by not using
// defaults in the constructor, we save a notable amount of memory.
const xMin = this.xMin || 0;
let yMin = this.yMin || 0;
const xMax = this.xMax || 0;
let yMax = this.yMax || 0;
const advanceWidth = this.advanceWidth || 0;
// Draw the glyph box
ctx.strokeStyle = 'blue';
draw.line(ctx, x + (xMin * scale), -10000, x + (xMin * scale), 10000);
draw.line(ctx, x + (xMax * scale), -10000, x + (xMax * scale), 10000);
draw.line(ctx, -10000, y + (-yMin * scale), 10000, y + (-yMin * scale));
draw.line(ctx, -10000, y + (-yMax * scale), 10000, y + (-yMax * scale));
// Draw the advance width
ctx.strokeStyle = 'green';
draw.line(ctx, x + (advanceWidth * scale), -10000, x + (advanceWidth * scale), 10000);
};
/**
* Convert the Glyph's Path to a string of path data instructions
* @param {object|number} [options={decimalPlaces:2, optimize:true, variation:undefined}] - Options object (or amount of decimal places for floating-point values for backwards compatibility)
* @param {opentype.Font} font - A font object is required if variation is to be applied in order to get the variation data from the tables
* @return {string}
* @see Path.toPathData
*/
Glyph.prototype.toPathData = function(options, font) {
options = Object.assign({}, { variation: font && font.defaultRenderOptions.variation }, options);
let useGlyph = this;
if(font && font.variation) {
useGlyph = font.variation.getTransform(this, options.variation);
}
let usePath = useGlyph.points && options.pointsTransform ? options.pointsTransform(useGlyph.points) : useGlyph.path;
if(options.pathTramsform) {
usePath = options.pathTramsform(usePath);
}
return usePath.toPathData(options);
};
/**
* Sets the path data from an SVG path element or path notation
* @param {string|SVGPathElement}
* @param {object}
*/
Glyph.prototype.fromSVG = function(pathData, options = {}) {
return this.path.fromSVG(pathData, options);
};
/**
* Convert the Glyph's Path to an SVG <path> element, as a string.
* @param {object|number} [options={decimalPlaces:2, optimize:true, variation:undefined}] - Options object (or amount of decimal places for floating-point values for backwards compatibility)
* @param {opentype.Font} font - A font object is required if variation is to be applied in order to get the variation data from the tables
* @return {string}
*/
Glyph.prototype.toSVG = function(options, font) {
const pathData = this.toPathData.apply(this, [options, font]);
return this.path.toSVG(options, pathData);
};
/**
* Convert the path to a DOM element.
* @param {object|number} [options={decimalPlaces:2, optimize:true, variation:undefined}] - Options object (or amount of decimal places for floating-point values for backwards compatibility)
* @param {opentype.Font} font - A font object is required if variation is to be applied in order to get the variation data from the tables
* @return {SVGPathElement}
*/
Glyph.prototype.toDOMElement = function(options, font) {
options = Object.assign({}, { variation: font && font.defaultRenderOptions.variation }, options);
let usePath = this.path;
if(font && font.variation) {
usePath = font.variation.getTransform(this, options.variation).path;
}
return usePath.toDOMElement(options);
};
export default Glyph;