当前位置:首页 >> 网络编程

JavaScript实现多球运动效果

本文实例为大家分享了JavaScript实现多球运动的具体代码,供大家参考,具体内容如下

JavaScript实现多球运动效果

代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>多球运动</title>
  <style>
    *{margin:0;padding:0;}
    body{background-color: #90f;}
    .ball{position: absolute;left:0;top:0;width:100px;height:100px;background: #f0f;border-radius: 50%;}
  </style>
</head>
<body>
  <script>
    run(22)//封装
    //定义速度
    var speed;
    function run(num){
      //创建出num个div
      for(var i=0;i<num;i++){
        //[2,11) 随机速度
        speed = Math.floor(Math.random()*9+2);
        //创建生成节点
        var div = document.createElement("div");
        //添加类名
        div.className = 'ball'
        //自定义属性保存值
        div.speedX = Math.floor(Math.random()*9+2)
        div.speedY = Math.floor(Math.random()*9+2)
        //将div放置到body中
        document.body.appendChild(div)
      }
      //获取元素
      var box = document.getElementsByClassName( "ball" )
      //获取文档可视区域的宽高
      var maxX = document.documentElement.clientWidth - box[0].offsetWidth;
      var maxY = document.documentElement.clientHeight - box[0].offsetHeight;
      //自适应窗口
      window.onresize = function(){
        maxX = document.documentElement.clientWidth - box[0].offsetWidth;
        maxY = document.documentElement.clientHeight - box[0].offsetHeight;
      }
      play()
      function play(){
        for(var i=0;i<num;i++){
          //获取
          var ball = box[i];
          var startTop = ball.offsetTop;
          var startLift = ball.offsetLeft;
          //startTop都为零;
          var top = startTop + ball.speedY;
          var left = startLift + ball.speedX;
          //判断小球是否出左右边界
          if(left <= 0 || left >= maxX){
            //改变方向
            ball.speedX = -ball.speedX;
            ball.style.background=randomColor()
            //判断
            if(left <= 0){
              left = 0;
            }else if(left >= maxX){
              left = maxX;
            }
          }
          //判断小球是否出上下边界
          if(top <= 0 || top >= maxY ){
            // 改变方向;
            ball.speedY = -ball.speedY; 
            ball.style.background=randomColor()
            //判断
            if( top <= 0 ){
              top = 0;
            }else if( top >= maxY ){
              top = maxY;
            }
          }
          ball.style.top = top + "px";
          ball.style.left = left + "px";          
        }
        //执行动画帧
        requestAnimationFrame(play);
      }
      //颜色随机
      function randomColor() {
        var r = Math.floor(Math.random() * 256),
          g = Math.floor(Math.random() * 256),
          b = Math.floor(Math.random() * 256);
          return "rgb(" + r + "," + g + "," + b + ")";
      }
    }
  </script>
</body>
</html>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。