canvas画布爆炸

<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <style>
    *{margin: 0;padding: 0;}
    html,body{background-color: #000;overflow: hidden;height: 100%;width: 100%;}
  </style>
</head>
<body>
  <canvas id="canvas"></canvas>
  <script>
    var  width = window.innerWidth,
      height= window.innerHeight,
      balls = [],
      timer,
      ci = 0,
      canvas = document.getElementById("canvas"),
      context = canvas.getContext("2d"),
      color = ['#da6b00', '#8555d4', '#4ad3b5', '#ffffff'];
    canvas.width = width;
    canvas.height = height;
    function drawBall(ball){
      context.beginPath();
      context.arc(ball.x,ball.y,ball.r,0,2*Math.PI);
      gradient = context.createRadialGradient(ball.x, ball.y, 0, ball.x, ball.y, ball.r/2);
      gradient.addColorStop(0, 'rgba(255,255,255,1)');
      gradient.addColorStop(0.2, ball.c);
      gradient.addColorStop(0.4, ball.c);
      gradient.addColorStop(1, 'rgba(0,0,0,1)');
      context.fillStyle = gradient;
      context.fill();
    }
    function init(){
      var ox = random(0,width),
         oy = random(0,height);
      gather(ox,oy);
      update();
      canvas.onclick = function(e){
        var ox = e.clientX,
        oy = e.clientY;
        gather(ox,oy)
      }
    }
    function update(){
      timer = setInterval(function(){
      context.clearRect(0,0,canvas.width,canvas.height);

      balls.forEach(function(ball,index){
        ball.x += ball.sx*2;
        ball.y += ball.sy*2;
        ball.r += ball.sr;

      if(ball.y > canvas.height)
        balls.splice(index,1)
      if(ball.y < 10)
        balls.splice(index,1)
      if(ball.x > canvas.width)
        balls.splice(index,1)
      if(ball.x < 10)
        balls.splice(index,1)

      if(balls.length<=100){
        var ox = random(0,width),
        oy = random(0,height);
        gather(ox,oy);
      }
      drawBall(ball)
    })

   },60)
  }
  function gather(ox,oy){
    var newBalls = []
    for(var i=0;i<400;i++){
      var c = color[ci++]
      ci = (ci>color.length-1)?0:ci;
      var x1 = random(ox-50,ox+50) ,x2;
      var y1 = random(oy-50,oy+50) ,y2;
      if(x1<ox){
        x2 = -random(1,10)
      }
      if(x1>ox){
        x2 = random(1,10)
      }
      if(y1<oy){
        y2 = -random(1,10)
      }
      if(y1>oy){
        y2 = random(1,10)
      }

      x2 = Math.random()>.5?x2:-x2;
      y2 = Math.random()>.5?y2:-y2;

      newBalls.push({
        x:x1,
        y:y1,
        r:random(1,10),
        c:c,
        sx:x2,
        sy:y2,
        sr:0.001,
      })

    }
    balls = balls.concat(newBalls);
  }
  function random(min,max){
    var mins = max-min;
    return Math.round(Math.random()*mins+min)
  }
  init();
</script>
</body>
</html>

posted @ 2017-08-28 14:56  罗章帅  阅读(254)  评论(0编辑  收藏  举报