-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtextBlock.js
More file actions
102 lines (88 loc) · 2.52 KB
/
Copy pathtextBlock.js
File metadata and controls
102 lines (88 loc) · 2.52 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
import { FONT, FONT_WEIGHT_NORMAL } from "./constants.js";
import { white } from "./colors.js";
import { clampedProgress, transition } from "./helpers.js";
import { easeOutExpo } from "./easings.js";
import { makeSpring } from "./spring.js";
export const makeTextBlock = (
canvasManager,
{
xPos,
yPos: initialYPos,
textAlign,
verticalAlign = "top",
fontSize = 24,
fontWeight = FONT_WEIGHT_NORMAL,
lineHeight = 32,
letterSpacing = "0px",
fill = white,
},
initialLinesArray
) => {
const CTX = canvasManager.getContext();
let textStart = Date.now();
let linesArray = [...initialLinesArray];
let verticalOffset =
verticalAlign === "center" ? (linesArray.length / 2) * lineHeight : 0;
let yPos = initialYPos;
const positionSpring = makeSpring(lineHeight, {
stiffness: 120,
damping: 13,
mass: 1,
precision: 120,
});
positionSpring.setEndValue(0);
const updateLines = (newLines) => {
textStart = Date.now();
positionSpring.resetValue();
positionSpring.setEndValue(0);
linesArray = [...newLines];
verticalOffset =
verticalAlign === "center" ? (linesArray.length / 2) * lineHeight : 0;
};
const updateYPos = (newYPos) => (yPos = newYPos);
const hide = () => positionSpring.setEndValue(-lineHeight);
const getBoundingBox = () => {
const leading = lineHeight - fontSize;
return {
top: yPos - verticalOffset + leading,
bottom: yPos - verticalOffset + leading + lineHeight * linesArray.length,
};
};
const draw = (deltaTime, delay = 0) => {
if (Date.now() - textStart > delay) {
positionSpring.update(deltaTime);
CTX.save();
CTX.font = `${fontWeight} ${fontSize}px ${FONT}`;
CTX.fillStyle = fill;
CTX.textAlign = textAlign;
CTX.letterSpacing = letterSpacing;
CTX.translate(xPos, yPos - verticalOffset);
linesArray.forEach((line, index) => {
const lineYPos = (index + 1) * lineHeight;
CTX.save();
// Draw clipping mask
CTX.beginPath();
CTX.rect(
-xPos,
lineYPos - fontSize,
canvasManager.getWidth(),
lineHeight
);
CTX.clip();
// Move text up into non clipped area
CTX.fillText(line, 0, lineYPos + positionSpring.getCurrentValue());
CTX.restore();
});
CTX.restore();
}
};
return {
draw,
getHeight: () => linesArray.length * lineHeight,
getBoundingBox,
getLines: () => linesArray,
updateLines,
updateYPos,
hide,
};
};