|
| 1 | +class CaptureText { |
| 2 | + constructor(textArray, speed = 0.7) { |
| 3 | + this.textArray = textArray; |
| 4 | + this.speed = speed; |
| 5 | + this.currentWordIndex = 0; |
| 6 | + this.textElements = document.querySelectorAll('.CaptureText'); |
| 7 | + this.loadAnimeJS().then(() => this.startTextAnimation()); |
| 8 | + } |
| 9 | + |
| 10 | + loadAnimeJS() { |
| 11 | + return new Promise((resolve, reject) => { |
| 12 | + if (typeof anime !== 'undefined') { |
| 13 | + resolve(); |
| 14 | + } else { |
| 15 | + const script = document.createElement('script'); |
| 16 | + script.src = 'https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js'; |
| 17 | + script.onload = resolve; |
| 18 | + script.onerror = reject; |
| 19 | + document.head.appendChild(script); |
| 20 | + } |
| 21 | + }); |
| 22 | + } |
| 23 | + |
| 24 | + animateText(element) { |
| 25 | + if (element) { |
| 26 | + element.innerHTML = this.textArray[this.currentWordIndex].replace( |
| 27 | + /\S/g, |
| 28 | + "<span style='display: inline-block;'>$&</span>" |
| 29 | + ); |
| 30 | + |
| 31 | + anime.timeline({ loop: false }) |
| 32 | + .add({ |
| 33 | + targets: `.${element.className} span`, |
| 34 | + scale: [4, 1], |
| 35 | + opacity: [0, 1], |
| 36 | + translateZ: 0, |
| 37 | + easing: "easeOutExpo", |
| 38 | + duration: 950 / this.speed, |
| 39 | + delay: (el, i) => (70 / this.speed) * i, |
| 40 | + }) |
| 41 | + .add({ |
| 42 | + targets: `.${element.className} span`, |
| 43 | + opacity: 0, |
| 44 | + duration: 1000, |
| 45 | + easing: "easeOutExpo", |
| 46 | + delay: 1000, |
| 47 | + }); |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + startTextAnimation() { |
| 52 | + this.textElements.forEach(element => this.animateText(element)); |
| 53 | + setInterval(() => { |
| 54 | + this.currentWordIndex = (this.currentWordIndex + 1) % this.textArray.length; |
| 55 | + this.textElements.forEach(element => this.animateText(element)); |
| 56 | + }, 2750 / this.speed); |
| 57 | + } |
| 58 | +} |
0 commit comments