躁动的小球

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>躁动的小球</title>
    <style media="screen">
      *{
        margin: 0px;
        padding: 0px;
      }
      #canvas{
        box-shadow: 0px 0px 10px black;
        display: block;
        margin: 50px auto;
        background: black;
      }
    </style>
  </head>
  <body>
    <canvas id="canvas" width="500" height="500"></canvas>

  </body>
  <script type="text/javascript">
    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");

    //随机函数
    function randomSize(min,max){
      return Math.floor(Math.random()*(max -min)+min);
    }
    function randomColor(){
      var r = randomSize(0,255);
      var g = randomSize(0,255);
      var b = randomSize(0,255);
       return "rgb(" + r +"," + g + "," + b+")";
    }

    //创建小球对象
    function Ball(){
      var speedX,speedY;
      //速度
      speedX = randomSize(1,6);
      speedY = randomSize(1,6);

      //半径
      this.r = randomSize(5,8);
      //圆心
      this.x = randomSize(this.r,canvas.width-this.r);
      this.y = randomSize(this.r,canvas.height -this.r);
      //方向
      this.speedX = randomSize(1,3) == 1 ? speedX : -speedX;
      this.speedY = randomSize(1,3) == 1 ? speedY : -speedY;
      //颜色
      this.color = randomColor();
    }
    //定义方法绘制小球
    Ball.prototype.draw = function(){
      ctx.beginPath();
      ctx.arc(this.x,this.y,this.r,0,360);
      ctx.closePath();
      ctx.fillStyle = this.color;
      ctx.fill();
    }
    //定义方法完成小球的移动
    Ball.prototype.move = function (){
      //改变中心的的x,y
      this.x+=this.speedX;
      this.y +=this.speedY;
    //进行边界判断
    if (this.x >=canvas.width-this.r) {
      this.speedX *=-1;
    } else if (this.x <=this.r) {
      this.speedX *=-1;
    }
    if (this.y >=canvas.height-this.r) {
      this.speedY *=-1;
    } else if (this.y <=this.r) {
      this.speedY *=-1;
    }
  }
  //生成小球对象
  var balls = [];
  for (var i = 0; i < 200; i++) {
    var ball = new Ball();
    balls.push(ball);
  }
  //让小球骚动起来
  function animation(){
    //每次动起来之前,清理之前的小球
    ctx.clearRect(0,0,canvas.width,canvas.height);
    //遍历小球数组,让每一个小球动起来
    for (var i = 0; i < balls.length; i++) {
      balls[i].move();
      balls[i].draw();
    };
      window.requestAnimationFrame(animation);
  }
  animation();

  </script>
</html>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值