JS 完成投掷骰子效果

803 阅读1分钟

平常小伙伴玩游戏可能会接触投骰子

随机1~6位数  判断大小来算输赢

今天我就用学习两天半的技术来写一个简陋的投骰子效果

思路:

1.准备7张图片 (1~6点 和一张动态骰子(gif)图)

2.获取标签

3.设定随机事件

代码如下:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      #btn {
        width: 80px;
        height: 35px;
        background-color: aquamarine;
        border: none;
        color: black;
        cursor: pointer;
        border-radius: 3px;
      }
      #btn:hover {
        background: rgba(118, 209, 179, 0.74);
      }
    </style>
  </head>
  <body>
    <img
      src="./img/1.png"
      alt=""
      style="width: 200px; height: 200px"
      id="img"
    />
    <button id="btn">开始摇摆</button>
 
    <script>
      var _btn = document.getElementById("btn");
      var _img = document.getElementById("img");
 
      //单击事件
      _btn.onclick = function () {
        //设置一个摇摆的图片
        _img.src = "./img/x.gif";
 
        setTimeout(function () {
          //随机点数
          var no = Math.ceil(Math.random() * 6);
          //设置图片
          _img.src = "./img/" + no + ".png";
        }, Math.ceil(Math.random() * 2000));
      };
    </script>
  </body>
</html>

效果如下:

image.png

由于我自身还没激活截取Gif图片的功能,就放了张静态图在这里 ,复制源码

加入图片(图片链接):

image.baidu.com/search/deta…

点击即可旋转起来