如何创建给定单词的动画字母增量,类似于动画数字计数器的工作方式? [英] How can I create animated letter increments of a given word similar to the way animated number counters work?

查看:126
本文介绍了如何创建给定单词的动画字母增量,类似于动画数字计数器的工作方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个动画字母增量器",该增量器可以接受任何给定的单词,并从A开始递增该单词的每个字母.

I'm creating an "animated letter incrementer" that takes any given word and increments each letter of that word starting from A.

示例:

Word = Dog

D - Increments from A to D [A, B, C, D]
O - Increments from A to O [A, B, C, D, E, F, G, H, I, J, K, L, M, N, O]
G - Increments from A to G [A, B, C, D, E, F, G]

我想要达到的效果类似于 jQuery动画数字计数器,我将增加字母而不是数字.另外,单词的每个字母应独立增加,但它们应同时到达目标字母.

The effect I'd like to achieve is similar to this jQuery animated number counter, except I'll be incrementing letters instead of counting numbers. Also, each letter of the word should increment independently, but they should all reach their destination letter at the same time.

JS:

var wordToIncrement = 'DOG';
var alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ '.split('');

for (var i = 0, len = wordToIncrement.length; i < len; i++) {

    var letterToIncrementTo = wordToIncrement[i];

    var arrayLength = alphabet.length;
    for (var z = 0; z < arrayLength; z++) {

        var alphabetLetter = alphabet[z];

        if (alphabetLetter == letterToIncrementTo) {

            console.log('MATCH FOUND!');
            console.log('Word Letter: ' + letterToIncrementTo);
            console.log('Alphabet Letter: ' + alphabetLetter);

            alphabetPositionValue = z;
            console.log('VALUE: ' + alphabetPositionValue);

            function incrementToLetter(letterToIncrementTo,alphabetPositionValue) {

                // This is where I'm stuck

                var div = document.getElementById('#word_block');
                div.innerHTML = div.innerHTML + 'Extra stuff';


            }

        }

    }

}

HTML:

<div id="work_block"></div>

如何完成以上代码,以实现与动画数字计数器示例相似的功能,并逐步增加单词的每个字母?我正在寻找基于JavaScript的解决方案.

How can I complete the code above to achieve similar functionality to the animated number counter example and increment through each letter of the word? I am looking for a javascript-based solution.

推荐答案

我将构建一个保留字母和时间的字母对象.这样,您可以在对象上提供简单的更新功能,并且对象本身将确保它产生正确的当前字母.

I would build a letter object maintaining the letter and timings. This way you can provide a simple update functionality on the object and the object will itself make sure it produces the correct current letter.

function Letter(table, letter, duration) {
  this.table = table;                          // lookup-table
  this.letter = letter;                        // target letter
  this.current = 0;                            // index in table
  this.delay = duration / tbl.indexOf(letter); // ms
  this.time = Date.now();                      // current (start) time
  this.done = false;                           // status
}

然后是一个通用的原型update()方法:

Then a common prototyped update() method:

Letter.prototype.update = function() {
  if (this.done) return;                       // if done, do no more
  var time = Date.now();                       // get current time
  if (time - this.time >= this.delay) {        // exceeded delay?
    this.time = time;                          // store current time
    if (this.letter === this.table[this.current] || 
        this.current === this.table.length) {  // target reached? unknown letter
      this.done = true;                        // we're done
    }
    else {
      this.current++;                          // next in table
    }
  }
};

然后我们可以从字符串中生成对象:

Then we can produce the objects from the string:

var letters = [];
word.toUpperCase().split("").forEach(function(l) {
  letters.push(new Letter(tbl, l, 2500));  // 2.5s duration
});

然后为其设置动画:

(function loop() {
   var txt = "", isDone = true;
   letters.forEach(function(l) {
     l.update();
     if (!l.done) isDone = false;
     txt += l.table[l.current];
   });

   // output txt
   if (!isDone) requestAnimationFrame(loop);
   else { /* done */ }
})();

演示

function Letter(table, letter, duration) {
  this.table = table;
  this.letter = letter;
  this.current = 0;
  this.delay = duration / tbl.indexOf(letter);   // ms
  this.time = Date.now();
  this.done = false;
}
Letter.prototype.update = function() {
  if (this.done) return;
  var time = Date.now();
  if (time - this.time >= this.delay) {
    this.time = time;
    if (this.letter === this.table[this.current] || 
        this.current === this.table.length) {
      this.done = true;
    }
    else {
      this.current++;
    }
  }
};

var word = "hello there";
var tbl = " ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var letters = [];
word.toUpperCase().split("").forEach(function(l) {
  letters.push(new Letter(tbl, l, 2500))
});

(function loop() {
  var txt = "", isDone = true;
  letters.forEach(function(l) {
    l.update();
    if (!l.done) isDone = false;
    txt += l.table[l.current];
  });

  // output txt
  d.innerHTML = txt;
  
  if (!isDone) requestAnimationFrame(loop);
  else { /* done */ }
})();

#d {font:bold 32px monospace}

<div id=d></div>

如果延迟低于16.7ms,则可能无法足够快地增加.可以通过将当前的相对时间除以持续时间来解决.将该标准化值与表中目标字母的索引相乘即可得到当前值,只需将结果四舍五入为整数值即可.

If the delay is below 16.7ms it may not increment fast enough. It can be solved by dividing current relative time on duration. Multiply this normalized value with index of the target letter in the table to get a current, just round the result to an integer value.

您可以提供不同的表格以获得随机性/变异性.

You can provide different tables to obtain randomness/variation.

这篇关于如何创建给定单词的动画字母增量,类似于动画数字计数器的工作方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆