▲TOPへ戻る

【javascript】サイコロを3Dアニメーションさせる方法

checkbox

以前にjavascriptでサイコロを作る方法を紹介しました。

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

しかし、2D表示で、ちょっと味気なかったので、サイコロを振っている間、サイコロをアニメーション表示させようと思います。

サイコロのアニメーション表示

  <div class="dice">
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
  </div>
  .dice {
    position: relative;
    width: 100px;
    height: 100px;
    transform-style: preserve-3d;
    animation: rotate-animation 1s linear infinite;
  }
  .dice .item {
    position: absolute;
    left: 0;
    right: 0;
    border: 1px solid #333;
    width: 100%;
    height: 100%;
  }
  /* 1 */
  .dice .item:nth-child(1) {
    transform: translate3d(0, -50px, 0) rotateX(-90deg);
    background: url() no-repeat
    center center / 100% 100%;
  }
  /* 2 */
  .dice .item:nth-child(2) {
    transform: translate3d(0, 0, 50px);
    background: url() no-repeat
    center center / 100% 100%;
  }
  /* 3 */
  .dice .item:nth-child(3) {
    transform: translate3d(50px, 0, 0) rotateY(90deg);
    background: url() no-repeat
    center center / 100% 100%;
  }
  /* 4 */
  .dice .item:nth-child(4) {
    transform: translate3d(-50px, 0, 0) rotateY(-90deg);
    background: url() no-repeat
    center center / 100% 100%;
  }
  /* 5 */
  .dice .item:nth-child(5) {
    transform: translate3d(0, 0, -50px) rotateY(180deg);
    background: url() no-repeat
    center center / 100% 100%;
  }
  /* 6 */
  .dice .item:nth-child(6) {
    transform: translate3d(0, 50px, 0) rotateX(-90deg);
    background: url() no-repeat
    center center / 100% 100%;
  }
  @keyframes rotate-animation {
    from {
      transform: rotate3d(1, 1, 1, 0deg);
    }
    25% {
      transform: rotate3d(1, 1, 1, 90deg);
    }
    50% {
      transform: rotate3d(1, 1, 1, 180deg);
    }
    75% {
      transform: rotate3d(1, 1, 1, 270deg);
    }
    to {
      transform: rotate3d(1, 1, 1, 360deg);
    }
  }

前回と今回のアニメーションを合わせたバージョン

サイコロ
  diceBtn1.addEventListener("click", function(){
      if(diceBtn1.textContent=='さいころを振る'){
          diceBtn1.textContent = 'ストップ';
          dice1.style.display = 'none'    // 最初の2Dサイコロ画像を非表示
          anidice1.style.display = 'block';   //  アニメーション用のサイコロを表示
          timerId1 = setInterval( () => {   //  隠したサイコロをランダムさせる
            let diceIndex1 = Math.floor(Math.random() * diceArry1.length) ;  
            dice1.src = diceArry1[diceIndex1];
          }, 200);
      }else{
          diceBtn1.textContent = 'さいころを振る';
          clearInterval(timerId1);    //  ランダムを停止
          anidice1.style.display = 'none'   //  アニメーションしていたサイコロを非表示
          dice1.style.display = 'block'
      }
  })

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

profile

パソコン好きなガオ

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

パソコン

javascript

カメラ

ブログ