尝试制作带有动画的随机字符串生成器

Trying to make a random string generator with animation

本文关键字:字符串 随机 动画 作带      更新时间:2023-09-26

我正在尝试创建一个带有动画的字符串随机化器,但它不起作用。

我使用此函数按照浏览器选择的帧速率调用该函数:

window.requestAnimFrame = (function(){
  return  window.requestAnimationFrame       || 
          window.webkitRequestAnimationFrame || 
          window.mozRequestAnimationFrame    || 
          window.oRequestAnimationFrame      || 
          window.msRequestAnimationFrame     || 
          function( callback,  element){
            window.setTimeout(callback, 1000 / 60);
          };
})();

然后是我生成和显示字符串的方法:

function create(chars,string_length){
output = [];
var randomstring = '';
    for (var i=0; i<string_length; i++) {
        var rnum = Math.floor(Math.random() * chars.length);
        randomstring += chars.substring(rnum,rnum+1);
    }

    output.push(randomstring);
    document.getElementById('cb').innerHTML = (output.join(''));
}

var chars =  "ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
var length = 20;
requestAnimFrame( create(chars,length) );

它为我的div 'id' 生成一个字符串,但只有一次 - 所以函数工作但不是一直被调用 =/

为什么会这样?

当你使用 requestAnimationFrame 时,它只会运行一次函数。您需要修改create()以再次调用 requestAnimationFrame 本身。此外,您还犯了另一个错误:您实际上是在调用create(chars, length)然后将结果传递给requestAnimationFrame,而不是将函数create()传递给requestAnimationFrame。这是一个应该有效的版本:

function create(chars,string_length){
    output = [];
    var randomstring = '';
    for (var i=0; i<string_length; i++) {
        var rnum = Math.floor(Math.random() * chars.length);
        randomstring += chars.substring(rnum,rnum+1);
    }

    output.push(randomstring);
    document.getElementById('cb').innerHTML = (output.join(''));
    requestAnimFrame(function(){ create(chars,string_length); });
}

var chars =  "ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
var length = 20;
requestAnimFrame(function(){ create(chars,length) });