forked from tleunen/pixi-multistyle-text
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpixi-multistyle-text.ts
553 lines (437 loc) · 15.1 KB
/
pixi-multistyle-text.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
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
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
/// <reference types="pixi.js" />
"use strict";
export interface ExtendedTextStyle extends PIXI.TextStyleOptions {
valign?: "top" | "middle" | "bottom";
}
export interface TextStyleSet {
[key: string]: ExtendedTextStyle;
}
interface FontProperties {
ascent: number;
descent: number;
fontSize: number;
}
interface TextData {
text: string;
style: ExtendedTextStyle;
width: number;
height: number;
fontProperties: FontProperties;
}
interface TextDrawingData {
text: string;
style: ExtendedTextStyle;
x: number;
y: number;
}
export default class MultiStyleText extends PIXI.Text {
private static DEFAULT_TAG_STYLE: ExtendedTextStyle = {
align: "left",
breakWords: false,
dropShadow: false,
dropShadowAngle: Math.PI / 6,
dropShadowBlur: 0,
dropShadowColor: "#000000",
dropShadowDistance: 5,
fill: "black",
fillGradientType: PIXI.TEXT_GRADIENT.LINEAR_VERTICAL,
fontFamily: "Arial",
fontSize: 26,
fontStyle: "normal",
fontVariant: "normal",
fontWeight: "normal",
letterSpacing: 0,
lineHeight: 0,
lineJoin: "miter",
miterLimit: 10,
padding: 0,
stroke: "black",
strokeThickness: 0,
textBaseline: "alphabetic",
wordWrap: false,
wordWrapWidth: 100
};
private textStyles: TextStyleSet;
constructor(text: string, styles: TextStyleSet) {
super(text);
this.styles = styles;
}
public set styles(styles: TextStyleSet) {
this.textStyles = {};
this.textStyles["default"] = this.assign({}, MultiStyleText.DEFAULT_TAG_STYLE);
for (let style in styles) {
if (style === "default") {
this.assign(this.textStyles["default"], styles[style]);
} else {
this.textStyles[style] = this.assign({}, styles[style]);
}
}
this._style = new PIXI.TextStyle(this.textStyles["default"]);
this.dirty = true;
}
public setTagStyle(tag: string, style: ExtendedTextStyle): void {
if (tag in this.textStyles) {
this.assign(this.textStyles[tag], style);
} else {
this.textStyles[tag] = this.assign({}, style);
}
this._style = new PIXI.TextStyle(this.textStyles["default"]);
this.dirty = true;
}
public deleteTagStyle(tag: string): void {
if (tag === "default") {
this.textStyles["default"] = this.assign({}, MultiStyleText.DEFAULT_TAG_STYLE);
} else {
delete this.textStyles[tag];
}
this._style = new PIXI.TextStyle(this.textStyles["default"]);
this.dirty = true;
}
private _getTextDataPerLine (lines: string[]) {
let outputTextData: TextData[][] = [];
let tags = Object.keys(this.textStyles).join("|");
let re = new RegExp(`<\/?(${tags})>`, "g");
let styleStack = [this.assign({}, this.textStyles["default"])];
// determine the group of word for each line
for (let i = 0; i < lines.length; i++) {
let lineTextData: TextData[] = [];
// find tags inside the string
let matches: RegExpExecArray[] = [];
let matchArray: RegExpExecArray;
while (matchArray = re.exec(lines[i])) {
matches.push(matchArray);
}
// if there is no match, we still need to add the line with the default style
if (matches.length === 0) {
lineTextData.push(this.createTextData(lines[i], styleStack[styleStack.length - 1]));
}
else {
// We got a match! add the text with the needed style
let currentSearchIdx = 0;
for (let j = 0; j < matches.length; j++) {
// if index > 0, it means we have characters before the match,
// so we need to add it with the default style
if (matches[j].index > currentSearchIdx) {
lineTextData.push(this.createTextData(
lines[i].substring(currentSearchIdx, matches[j].index),
styleStack[styleStack.length - 1]
));
}
if (matches[j][0][1] === "/") { // reset the style if end of tag
if (styleStack.length > 1) {
styleStack.pop();
}
} else { // set the current style
styleStack.push(this.assign({}, styleStack[styleStack.length - 1], this.textStyles[matches[j][1]]));
}
// update the current search index
currentSearchIdx = matches[j].index + matches[j][0].length;
}
// is there any character left?
if (currentSearchIdx < lines[i].length) {
lineTextData.push(this.createTextData(
lines[i].substring(currentSearchIdx),
styleStack[styleStack.length - 1]
));
}
}
outputTextData.push(lineTextData);
}
return outputTextData;
}
private getFontString(style: ExtendedTextStyle): string {
return new PIXI.TextStyle(style).toFontString();
}
private createTextData(text: string, style: ExtendedTextStyle): TextData {
return {
text,
style,
width: 0,
height: 0,
fontProperties: undefined
};
}
private getDropShadowPadding(): number {
let maxDistance = 0;
let maxBlur = 0;
Object.keys(this.textStyles).forEach((styleKey) => {
let { dropShadowDistance, dropShadowBlur } = this.textStyles[styleKey];
maxDistance = Math.max(maxDistance, dropShadowDistance || 0);
maxBlur = Math.max(maxBlur, dropShadowBlur || 0);
});
return maxDistance + maxBlur;
}
public updateText(): void {
if (!this.dirty) {
return;
}
this.texture.baseTexture.resolution = this.resolution;
let textStyles = this.textStyles;
let outputText = this.text;
if(this._style.wordWrap) {
outputText = this.wordWrap(this.text);
}
// split text into lines
let lines = outputText.split(/(?:\r\n|\r|\n)/);
// get the text data with specific styles
let outputTextData = this._getTextDataPerLine(lines);
// calculate text width and height
let lineWidths: number[] = [];
let lineHeights: number[] = [];
let maxLineWidth = 0;
for (let i = 0; i < lines.length; i++) {
let lineWidth = 0;
let lineHeight = 0;
for (let j = 0; j < outputTextData[i].length; j++) {
let sty = outputTextData[i][j].style;
this.context.font = this.getFontString(sty);
// save the width
outputTextData[i][j].width = this.context.measureText(outputTextData[i][j].text).width;
if (outputTextData[i][j].text.length === 0) {
outputTextData[i][j].width += (outputTextData[i][j].text.length - 1) * sty.letterSpacing;
if (j > 0) {
lineWidth += sty.letterSpacing / 2; // spacing before first character
}
if (j < outputTextData[i].length - 1) {
lineWidth += sty.letterSpacing / 2; // spacing after last character
}
}
lineWidth += outputTextData[i][j].width;
// save the font properties
outputTextData[i][j].fontProperties = PIXI.TextMetrics.measureFont(this.context.font);
// save the height
outputTextData[i][j].height =
outputTextData[i][j].fontProperties.fontSize + outputTextData[i][j].style.strokeThickness;
lineHeight = Math.max(lineHeight, outputTextData[i][j].height);
}
lineWidths[i] = lineWidth;
lineHeights[i] = lineHeight;
maxLineWidth = Math.max(maxLineWidth, lineWidth);
}
// transform styles in array
let stylesArray = Object.keys(textStyles).map((key) => textStyles[key]);
let maxStrokeThickness = stylesArray.reduce((prev, curr) => Math.max(prev, curr.strokeThickness || 0), 0);
let dropShadowPadding = this.getDropShadowPadding();
let maxLineHeight = lineHeights.reduce((prev, curr) => Math.max(prev, curr), 0);
// define the right width and height
let width = maxLineWidth + maxStrokeThickness + 2 * dropShadowPadding;
let height = (maxLineHeight * lines.length) + 2 * dropShadowPadding;
this.canvas.width = (width + this.context.lineWidth) * this.resolution;
this.canvas.height = height * this.resolution;
this.context.scale(this.resolution, this.resolution);
this.context.textBaseline = "alphabetic";
this.context.lineJoin = "round";
let basePositionY = dropShadowPadding;
let drawingData: TextDrawingData[] = [];
// Compute the drawing data
for (let i = 0; i < outputTextData.length; i++) {
let line = outputTextData[i];
let linePositionX: number;
switch (this._style.align) {
case "left":
linePositionX = dropShadowPadding;
break;
case "center":
linePositionX = dropShadowPadding + (maxLineWidth - lineWidths[i]) / 2;
break;
case "right":
linePositionX = dropShadowPadding + maxLineWidth - lineWidths[i];
break;
}
for (let j = 0; j < line.length; j++) {
let { style, text, fontProperties } = line[j];
linePositionX += maxStrokeThickness / 2;
let linePositionY = maxStrokeThickness / 2 + basePositionY + fontProperties.ascent;
if (style.valign === "bottom") {
linePositionY += lineHeights[i] - line[j].height - (maxStrokeThickness - style.strokeThickness) / 2;
} else if (style.valign === "middle") {
linePositionY += (lineHeights[i] - line[j].height) / 2 - (maxStrokeThickness - style.strokeThickness) / 2;
}
if (style.letterSpacing === 0) {
drawingData.push({
text,
style,
x: linePositionX,
y: linePositionY
});
linePositionX += line[j].width;
} else {
this.context.font = this.getFontString(line[j].style);
for (let k = 0; k < text.length; k++) {
if (k > 0 || j > 0) {
linePositionX += style.letterSpacing / 2;
}
drawingData.push({
text: text.charAt(k),
style,
x: linePositionX,
y: linePositionY
});
linePositionX += this.context.measureText(text.charAt(k)).width;
if (k < text.length - 1 || j < line.length - 1) {
linePositionX += style.letterSpacing / 2;
}
}
}
linePositionX -= maxStrokeThickness / 2;
}
basePositionY += lineHeights[i];
}
this.context.save();
// First pass: draw the shadows only
drawingData.forEach(({ style, text, x, y }) => {
if (!style.dropShadow) {
return; // This text doesn't have a shadow
}
this.context.font = this.getFontString(style);
let dropFillStyle = style.dropShadowColor;
if (typeof dropFillStyle === "number") {
dropFillStyle = PIXI.utils.hex2string(dropFillStyle);
}
this.context.shadowColor = dropFillStyle;
this.context.shadowBlur = style.dropShadowBlur;
this.context.shadowOffsetX = Math.cos(style.dropShadowAngle) * style.dropShadowDistance * this.resolution;
this.context.shadowOffsetY = Math.sin(style.dropShadowAngle) * style.dropShadowDistance * this.resolution;
this.context.fillText(text, x, y);
});
this.context.restore();
// Second pass: draw strokes and fills
drawingData.forEach(({ style, text, x, y }) => {
this.context.font = this.getFontString(style);
let strokeStyle = style.stroke;
if (typeof strokeStyle === "number") {
strokeStyle = PIXI.utils.hex2string(strokeStyle);
}
this.context.strokeStyle = strokeStyle;
this.context.lineWidth = style.strokeThickness;
// set canvas text styles
let fillStyle = style.fill;
if (typeof fillStyle === "number") {
fillStyle = PIXI.utils.hex2string(fillStyle);
} else if (Array.isArray(fillStyle)) {
for (let i = 0; i < fillStyle.length; i++) {
let fill = fillStyle[i];
if (typeof fill === "number") {
fillStyle[i] = PIXI.utils.hex2string(fill);
}
}
}
this.context.fillStyle = this._generateFillStyle(new PIXI.TextStyle(style), [text]) as string | CanvasGradient;
// Typecast required for proper typechecking
if (style.stroke && style.strokeThickness) {
this.context.strokeText(text, x, y);
}
if (style.fill) {
this.context.fillText(text, x, y);
}
});
this.updateTexture();
}
protected wordWrap(text: string): string {
// Greedy wrapping algorithm that will wrap words as the line grows longer than its horizontal bounds.
let result = '';
let tags = Object.keys(this.textStyles).join("|");
let re = new RegExp(`(<\/?(${tags})>)`, "g");
const lines = text.split("\n");
const wordWrapWidth = this._style.wordWrapWidth;
let styleStack = [this.assign({}, this.textStyles["default"])];
this.context.font = this.getFontString(this.textStyles["default"]);
for (let i = 0; i < lines.length; i++) {
let spaceLeft = wordWrapWidth;
const words = lines[i].split(" ");
for (let j = 0; j < words.length; j++) {
const parts = words[j].split(re);
for (let k = 0; k < parts.length; k++) {
if (re.test(parts[k])) {
result += parts[k];
if (parts[k][1] === "/") {
k++;
styleStack.pop();
} else {
k++;
styleStack.push(this.assign({}, styleStack[styleStack.length - 1], this.textStyles[parts[k]]));
}
this.context.font = this.getFontString(styleStack[styleStack.length - 1]);
continue;
}
const partWidth = this.context.measureText(parts[k]).width;
if (this._style.breakWords && partWidth > spaceLeft) {
// Part should be split in the middle
const characters = parts[k].split('');
if (j > 0 && k === 0) {
result += " ";
spaceLeft -= this.context.measureText(" ").width;
}
for (let c = 0; c < characters.length; c++) {
const characterWidth = this.context.measureText(characters[c]).width;
if (characterWidth > spaceLeft) {
result += `\n${characters[c]}`;
spaceLeft = wordWrapWidth - characterWidth;
} else {
if (j > 0 && k === 0 && c === 0) {
result += " ";
}
result += characters[c];
spaceLeft -= characterWidth;
}
}
} else if(this._style.breakWords) {
result += parts[k];
spaceLeft -= partWidth;
} else {
const paddedPartWidth =
partWidth + (k === 0 ? this.context.measureText(" ").width : 0);
if (j === 0 || paddedPartWidth > spaceLeft) {
// Skip printing the newline if it's the first word of the line that is
// greater than the word wrap width.
if (j > 0) {
result += "\n";
}
result += parts[k];
spaceLeft = wordWrapWidth - partWidth;
} else {
spaceLeft -= paddedPartWidth;
if (k === 0) {
result += " ";
}
result += parts[k];
}
}
}
}
if (i < lines.length - 1) {
result += '\n';
}
}
return result;
}
protected updateTexture() {
const texture = this._texture;
let dropShadowPadding = this.getDropShadowPadding();
texture.baseTexture.hasLoaded = true;
texture.baseTexture.resolution = this.resolution;
texture.baseTexture.realWidth = this.canvas.width;
texture.baseTexture.realHeight = this.canvas.height;
texture.baseTexture.width = this.canvas.width / this.resolution;
texture.baseTexture.height = this.canvas.height / this.resolution;
texture.trim.width = texture.frame.width = this.canvas.width / this.resolution;
texture.trim.height = texture.frame.height = this.canvas.height / this.resolution;
texture.trim.x = -this._style.padding - dropShadowPadding;
texture.trim.y = -this._style.padding - dropShadowPadding;
texture.orig.width = texture.frame.width - (this._style.padding + dropShadowPadding) * 2;
texture.orig.height = texture.frame.height - (this._style.padding + dropShadowPadding) * 2;
// call sprite onTextureUpdate to update scale if _width or _height were set
this._onTextureUpdate();
texture.baseTexture.emit('update', texture.baseTexture);
this.dirty = false;
}
// Lazy fill for Object.assign
private assign(destination: any, ...sources: any[]): any {
for (let source of sources) {
for (let key in source) {
destination[key] = source[key];
}
}
return destination;
}
}