-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtext_transition.js
91 lines (76 loc) · 2.33 KB
/
text_transition.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
82
83
84
85
86
87
88
89
90
91
/**
* Changes the contents of the target HTML with a new value, transitioning characters individually in a random fashion.
*/
function textTransition({
element,
newText,
maxDuration = 1000,
entropy = 0.8,
rate = 125,
highlight = "#f4c862",
}) {
let currentTextCharCodeArray = element.textContent
.split("")
.map((letter) => letter.charCodeAt(0));
let newTextCharCodeArray = newText
.split("")
.map((letter) => letter.charCodeAt(0));
let transitionTextCharCodeArray = new Array(newText.length);
requestAnimationFrame(_textTransition);
let previousTick = 0;
let rateCounter = 0;
let intervalCounter = 0;
function _textTransition(timestamp) {
const delta = timestamp - previousTick;
previousTick = timestamp;
intervalCounter += delta;
rateCounter += delta;
if (intervalCounter >= rate) {
intervalCounter = 0;
transitionTextCharCodeArray = newTextCharCodeArray.map(
(charCode, idx) => {
if (
charCode === currentTextCharCodeArray[idx] ||
charCode === transitionTextCharCodeArray[idx]?.charCode ||
Math.random() > entropy
) {
return {
charCode,
done: true,
};
}
// included characters: A-Z a-z 0-9 "#$%&\'()*+,-./:;<=>?@[\\]^_`{|}
const randomNum = Math.max(32, Math.floor(Math.random() * 126));
return {
charCode: randomNum,
done: false,
};
}
);
if (rateCounter >= maxDuration) {
element.textContent = newText;
return;
}
if (!highlight) {
element.textContent = transitionTextCharCodeArray
.map(({ charCode }) => String.fromCharCode(charCode))
.join("");
return;
}
element.innerHTML = transitionTextCharCodeArray
.map(({ charCode, done }) => {
let color = "";
if (highlight instanceof Array) {
color = highlight[Math.floor(Math.random() * highlight.length)];
}
return done
? `<span>${String.fromCharCode(charCode)}</span>`
: `<span style="color: ${color || highlight}">${String.fromCharCode(
charCode
)}</span>`;
})
.join("");
}
requestAnimationFrame(_textTransition);
}
}