0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

「タイピングソフトを作ろう!」JavaScrpt初級~中級者向け(FileAPIを使用)

Last updated at Posted at 2022-03-03

Youtubeで公開した「タイピングソフトを作ろう!」の内容を記事にしました。

◆「タイピングソフトを作ろう!」トレーニング編

タイトル 動画🔗
前編 https://youtu.be/gRde88oundY
後編 https://youtu.be/Cqu6Zuj24wo

◆ サンプルファイル

Github からダウンロードしてご利用ください
https://github.com/yamazakidaisuke/keytyping_youtube

◆ どんなキータイピングアプリ?

外部ファイルでキーワードを管理します、以下のように並べるだけ。
これはJavaScriptでFileApiを利用することで可能になります。

以下画面構成を見ていただければわかりますが、
上記のテキストファイルを読み込めば、オリジナルのキーワードをタイピングできます!!

◆ 変数を準備

keytyping.html
//***************************************
//グローバル変数
//***************************************
const G = {
    read_file : document.getElementById("file"),          //File選択
    output_text : document.getElementById("output_text"), //キーワード表示
    input_text : document.getElementById("input_text"),   //キーワード入力
    start : document.getElementById("start"),             //スタートボタン
    total : document.getElementById("total"),             //点数表示
    texts : [], //配列でキーワード入ってくる                //読み込んだキーワードを配列で保持
    score : 0                                             //点数を保持
}

◆関数(処理)を記述

keytyping.html
//***************************************
//関数
//***************************************
//ファイルを選択読み込む(FileAPIを利用)
function readFile(e){
    const file = e.target.files[0];  //ファイル情報を代入
    const reader = new FileReader(); //インスタンス化
    reader.onload = function(){      //読込み完了後にloadする
        G.texts = reader.result.split("\n"); //配列変換して代入
    };
    reader.readAsText(file);  //textFileをRead
}

//テキストをランダムに表示
function shuffleText(){
    G.input_text.value="";            //入力文字を削除
    const rf = Math.random() * G.texts.length;
    const r  = Math.floor(rf);        //整数の乱数を作成
    G.output_text.value = G.texts[r]; //n番目テキストを表示
}

//キーを押すたびに処理
function keyEvent(e){
    if(G.output_text.value === G.input_text.value){
        shuffleText();   //ランダムにテキストを再表示
        G.score++;       //スコアに+1
        G.total.textContent = G.score;  //表示を入れ替える
    }
}

◆ イベントと関数の紐づけ

keytyping.html
//***************************************
//イベントと関数の紐づけ
//***************************************
G.start.onclick = shuffleText;
G.read_file.onchange = readFile;
G.input_text.onkeydown = keyEvent;
以下Youtube動画で詳しく解説してるのでどうぞ見てください

◆ どうでしたか?

そこそこできる人は上記の解説・コードで十分だったかと思いますが、
初学者であれば、動画で詳しくやってみてください。

以上

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?