-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathanimate.js
82 lines (66 loc) · 2.48 KB
/
animate.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
const lettersPerFrame = 0.6;
const frameDuration = 1000/30;
const letterIter = 20;
const letterShow = 10;
function animate() {
// if (window.localStorage && !window.localStorage.getItem('animated')){
document.body.style.opacity = 1;
window.localStorage.setItem('animated', '1');
animateElement(document.body);
// } else {
// document.body.style.opacity = 1;
// }
}
function animateElement(el) {
const nodes = el.childNodes;
for (let i = 0; i < nodes.length; i++) {
if (nodes[i].hasChildNodes()) {
animateElement(nodes[i]);
} else if (nodes[i].textContent.trim().length > 0) {
animateNode(nodes[i]);
}
}
}
function animateNode(node) {
let content = node.textContent.split('').map((char, index) => ({
char,
index,
iter: letterIter
})).filter(el => el.char !== ' ');
const loopsPerFrame = Math.max(1, Math.round(content.length * lettersPerFrame));
node.textContent = node.textContent.replace(/[^ ]/gm, '\u2002');
let loop = () => {
for (let i = 0; i < loopsPerFrame; i++) {
if (content.length === 0) { return; }
const index = Math.floor(Math.random() * content.length);
const charObject = content[index];
charObject.iter -= 1;
if (charObject.iter <= 0 || node.textContent[charObject.index] == charObject.char || node.textContent[charObject.index] == '\u00A0') {
node.textContent = setChar(node.textContent, charObject.index, charObject.char);
content.splice(index, 1);
} else if (charObject.iter <= letterShow) {
node.textContent = setChar(node.textContent, charObject.index, randomChar());
}
}
setTimeout(loop, frameDuration);
}
setTimeout(loop, frameDuration);
}
function randomizeChar(charList) {
if (charList.length === 0) { return false; }
return charList.length > 0;
}
function setChar (string, index, char) {
return string.substr(0, index) + char + string.substr(index + 1)
}
function randomChar() {
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@%$?/*&^(){}[]|\\"\':;.,<>`~±§';
return characters.charAt(Math.floor(Math.random() * characters.length));
}
try {
animate();
document.getElementById('rerun-animation').onclick = () => animateElement(document.body);
} catch(e) {
console.log(e);
document.body.style.opacity = 1;
}