▲TOPへ戻る

【Javascript】画像をランダム表示させ、ボードゲーム用のサイコロを作る

ゲーム用に以下のようなさいころを作ってみました。

html

 <section class="diceContent">
    <img id="dice"></img>  //  ここに画像を表示
    <button type="button" id="diceBtn">さいころを振る</button>
    </section>

CSS

   .diceContent{
        width: 360px;
        height: 200px;
        margin: 30px auto;
        background: #333;
        border-radius: 20px;
        position: relative;
    }
    #diceBtn{
        position: absolute;
        width: 150px;
        height: 30px;
        bottom: 20px;
        left: 50%;
        transform: translate(-50%);
        border-radius: 10px;
    }
    #dice{
        position: absolute;
        width: 120px;
        top: 20px;
        left: 50%;
        transform: translate(-50%);
    }

javascript

 let diceArry = ['(画像のパス)/1さいころ.jpg',
                '(画像のパス)/2さいころ.jpg',
                '(画像のパス)/3さいころ.jpg',
                '(画像のパス)/4さいころ.jpg',
                '(画像のパス)/5さいころ.jpg',
                '(画像のパス)/6さいころ.jpg'
                ];  //  画像の配列
    const dice = document.getElementById("dice");  //  ここに画像を表示
    const diceBtn = document.getElementById("diceBtn");  //  ボタン
    dice.src = diceArry[0];  //  最初の画面

    diceBtn.addEventListener("click", function(){
        if(diceBtn.textContent=='さいころを振る'){
         diceBtn.textContent = 'ストップ'  //  ボタンの表示を変える
            timerId = setInterval( () => {
           let diceIndex = Math.floor(Math.random() * diceArry.length) ;  
            dice.src = diceArry[diceIndex];
         }, 200);   //  ランダム表示
        }else{
         diceBtn.textContent = 'さいころを振る';  //  ボタンの表示を変える
         clearInterval(timerId);   //  ランダム表示の停止
        }
    })

まとめ

point

画像のパスの配列を作る。

Math.floor(Math.random() * arry.length)でランダムさせる。

setIntervalでランダム表示を繰り返す。

ボタンでスタートとストップを制御する。

こんな記事も読まれています。

profile

パソコン好きなガオ

コロナ禍によるステイホームを機にプログラミングを学ぶ。パソコンに関してはプロではないが、ちょっと詳しい程度。

パソコン

javascript

カメラ

ブログ