JSで文字をシャッフルしながら1文字ずつ出現させる

2025/09/12 (金) - 10:00 JavaScript

見出しやナビの文字をランダムな文字でシャッフルしながら1文字ずつ出現するやつをJavaScriptで作りました。

昔、ActionScript 3.0(AS3)で作ったライブラリを無理矢理JavaScriptに書き換えた物なので、綺麗なコードではありませんが…。使い方としては、あらかじめHTML要素に文字を用意しておき、シャッフルテキスト用テキスト要素を指定したインスタンスを生成します。その後よきタイミング(ボタンを押下したり、スクロールが動いたタイミングなど)でplay();メソッドを実行すると対象のテキストがシャッフルします。

見出しなどあくまで短い文章向けのエフェクトなので、本文などに指定するのは避けるべきです。

HTMLのコード

<p id="txt">Chu!可愛くてごめん</p>
<button type="button" id="btn">シャッフルする</button>

実行させるためのJavaScript

const txt = document.getElementById('txt');
const btn = document.getElementById('btn');
const shuffle = new shuffleTxt(txt);
btn.addEventListener('click',function(){
 shuffle.play(); //ボタンを押下したら文字をシャッフル
});

本体のコード

const fps = 60; //インターバル 小さい値にすると遅くなる
class shuffleTxt{
 constructor(target){
  this.isFlg = false;
  this.targetEl = target;
  this.strBase = this.targetEl.textContent;
  this.strRandom = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!?#$%&|/*+-=;_:'
  this.strComplete = '';
  this.intRemaining= this.strBase.length;
  this.intNowCnt = 0;
  this.intStartTime = 0;
  this.intNowTime;
  this.intFPS = 1000/fps;
  this.timeID;
 }
 play(){
  if(this.isFlg){
   return false;
  }else{
   this.isFlg = true;
   this.targetEl.textContent = '';
   this.searchTxt();
  }
 }
 stop(){
  this.intNowCnt = 0;
  this.intStartTime = 0;
  this.intNowTime = 0;
  this.intRemaining = this.strBase.length;
  this.targetEl.textContent = this.strBase;
  this.isFlg = false;
 }
 searchTxt(){
  let difTime;
  if(this.strBase.length >= this.intNowCnt){
   this.strComplete = this.strBase.substr(0,this.intNowCnt);
   this.timeID = requestAnimationFrame(() => {
    this.intNowTime = new Date().getTime();
    difTime = this.intNowTime - this.intStartTime;
    if ( difTime >= this.intFPS ) {
     this.intStartTime = this.intNowTime;
     this.randomTxt();
    }else{
     this.searchTxt();
    }
   }); 
  }else{
   cancelAnimationFrame(this.timeID);
   this.stop();
  }
 }
 randomTxt(){
  let str = '';
  for (let i=0; i<=this.intRemaining; i++){
   str += this.strRandom.charAt(Math.floor(Math.random()*this.strRandom.length))
  }
  this.targetEl.textContent = this.strComplete + str;
  this.intNowCnt++;
  this.intRemaining--;
  this.searchTxt();
 }
}

おしまい

記事をシェアする

  • facebookでシェアする
  • twitter(X)でシェアする
  • LINEでシェアする
  • はてなブックマークでシェアする
  • Threadsでシェアする
  • Pocketでシェアする
  • Pinterestでシェアする

おすすめ記事

トラックバック & ピンバック

この記事へのトラックバックURI
https://weblog.walk-life.me/js_shuffle_txt/trackback/

コメント

コメントは下記からどうぞ

ページの先頭へ