Advertisement
Guest User

Kontol

a guest
Oct 15th, 2019
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // ——————————————————————————————————————————————————
  2. // TextScramble
  3. // ——————————————————————————————————————————————————
  4.  
  5. class TextScramble {
  6.   constructor(el) {
  7.     this.el = el
  8.     this.chars = '!<>-_\\/[]{}—=+*^?#________'
  9.     this.update = this.update.bind(this)
  10.   }
  11.   setText(newText) {
  12.     const oldText = this.el.innerText
  13.     const length = Math.max(oldText.length, newText.length)
  14.     const promise = new Promise((resolve) => this.resolve = resolve)
  15.     this.queue = []
  16.     for (let i = 0; i < length; i++) {
  17.       const from = oldText[i] || ''
  18.       const to = newText[i] || ''
  19.       const start = Math.floor(Math.random() * 40)
  20.       const end = start + Math.floor(Math.random() * 40)
  21.       this.queue.push({ from, to, start, end })
  22.     }
  23.     cancelAnimationFrame(this.frameRequest)
  24.     this.frame = 0
  25.     this.update()
  26.     return promise
  27.   }
  28.   update() {
  29.     let output = ''
  30.     let complete = 0
  31.     for (let i = 0, n = this.queue.length; i < n; i++) {
  32.       let { from, to, start, end, char } = this.queue[i]
  33.       if (this.frame >= end) {
  34.         complete++
  35.         output += to
  36.       } else if (this.frame >= start) {
  37.         if (!char || Math.random() < 0.28) {
  38.           char = this.randomChar()
  39.           this.queue[i].char = char
  40.         }
  41.         output += `<span class="dud">${char}</span>`
  42.       } else {
  43.         output += from
  44.       }
  45.     }
  46.     this.el.innerHTML = output
  47.     if (complete === this.queue.length) {
  48.       this.resolve()
  49.     } else {
  50.       this.frameRequest = requestAnimationFrame(this.update)
  51.       this.frame++
  52.     }
  53.   }
  54.   randomChar() {
  55.     return this.chars[Math.floor(Math.random() * this.chars.length)]
  56.   }
  57. }
  58.  
  59. // ——————————————————————————————————————————————————
  60. // Example
  61. // ——————————————————————————————————————————————————
  62.  
  63. const phrases = [
  64.   'Neo,',
  65.   'sooner or later',
  66.   'you\'re going to realize',
  67.   'just as I did',
  68.   'that there\'s a difference',
  69.   'between knowing the path',
  70.   'and walking the path'
  71. ]
  72.  
  73. const el = document.querySelector('.text')
  74. const fx = new TextScramble(el)
  75.  
  76. let counter = 0
  77. const next = () => {
  78.   fx.setText(phrases[counter]).then(() => {
  79.     setTimeout(next, 800)
  80.   })
  81.   counter = (counter + 1) % phrases.length
  82. }
  83.  
  84. next()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement