-
Notifications
You must be signed in to change notification settings - Fork 7.1k
/
GetTextSize.js
81 lines (66 loc) · 2.1 KB
/
GetTextSize.js
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
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2013-2023 Photon Storm Ltd.
* @license {@link https://opensource.org/licenses/MIT|MIT License}
*/
/**
* Returns an object containing dimensions of the Text object.
*
* @function Phaser.GameObjects.GetTextSize
* @since 3.0.0
*
* @param {Phaser.GameObjects.Text} text - The Text object to calculate the size from.
* @param {Phaser.Types.GameObjects.Text.TextMetrics} size - The Text metrics to use when calculating the size.
* @param {string[]} lines - The lines of text to calculate the size from.
*
* @return {Phaser.Types.GameObjects.Text.GetTextSizeObject} An object containing dimensions of the Text object.
*/
var GetTextSize = function (text, size, lines)
{
var canvas = text.canvas;
var context = text.context;
var style = text.style;
var lineWidths = [];
var maxLineWidth = 0;
var drawnLines = lines.length;
if (style.maxLines > 0 && style.maxLines < lines.length)
{
drawnLines = style.maxLines;
}
style.syncFont(canvas, context);
// Text Width
for (var i = 0; i < drawnLines; i++)
{
var lineWidth = style.strokeThickness;
lineWidth += context.measureText(lines[i]).width;
if (lines[i].length > 1)
{
lineWidth += text.letterSpacing * (lines[i].length - 1);
}
// Adjust for wrapped text
if (style.wordWrap)
{
lineWidth -= context.measureText(' ').width;
}
lineWidths[i] = Math.ceil(lineWidth);
maxLineWidth = Math.max(maxLineWidth, lineWidths[i]);
}
// Text Height
var lineHeight = size.fontSize + style.strokeThickness;
var height = lineHeight * drawnLines;
var lineSpacing = text.lineSpacing;
// Adjust for line spacing
if (drawnLines > 1)
{
height += lineSpacing * (drawnLines - 1);
}
return {
width: maxLineWidth,
height: height,
lines: drawnLines,
lineWidths: lineWidths,
lineSpacing: lineSpacing,
lineHeight: lineHeight
};
};
module.exports = GetTextSize;