利用html5實現的飛雪效果程式碼例項

antzone發表於2017-03-15

本章節分享一段程式碼例項,它利用html5實現了漫天飛雪的效果。

有需要的朋友可以做一下參考,程式碼其實也非常的簡單,這裡就不多介紹了。

程式碼如下:

[HTML] 純文字檢視 複製程式碼
<!DOCTYPE html>
<html>
<head>
  <meta charset=" utf-8">
  <meta name="author" content="http://www.softwhy.com/" />
  <title>螞蟻部落</title>
  <style type="text/css">
    * {
      margin: 0;
      padding: 0;
    }

    body {
      background: #6b92b9;
    }

    canvas {
      display: block;
    }
  </style>
</head>
<body>
  <div style="background:#6b92b9; width:100%;height:2000px;"></div>
  <canvas id="canvas" style="position:fixed;top:0px;left:0px;pointer-events:none;"></canvas>
  <script type="text/javascript">
window.onload=function(){
  //canvas init
  var canvas=document.getElementById("canvas");
  var ctx=canvas.getContext("2d");

  //canvas dimensions
  var W=window.innerWidth;
  var H=window.innerHeight;
  canvas.width=W;
  canvas.height=H;

  //snowflake particles
  var mp = 3000; //max particles
  var particles = [];
  for(var i = 0; i < mp; i++){
    particles.push({
      x: Math.random()*W, //x-coordinate
      y: Math.random()*H, //y-coordinate
      r: Math.random()*3+1, //radius
      d: Math.random()*mp //density
    })
  }

  //Lets draw the flakes
  function draw(){
    ctx.clearRect(0, 0, W, H);
    ctx.fillStyle = "rgba(255, 255, 255, 0.8)";
    /* ctx.fillStyle = "#FF0000";*/
    ctx.beginPath();
    for(var i = 0; i < mp; i++){
      var p = particles[i];
      ctx.moveTo(p.x, p.y);
      ctx.arc(p.x, p.y, p.r, 0, Math.PI*2, true);
    }
    ctx.fill();
    update();
  }

  //Function to move the snowflakes
  var angle = 0;
  function update(){
    angle += 0.01;
    for(var i = 0; i < mp; i++){
      var p = particle[i];
      p.y += Math.cos(angle+p.d) + 1 + p.r/2;
      p.x += Math.sin(angle) * 2;

      if(p.x > W || p.x < 0 || p.y > H){
        if(i%3 > 0){
          particles[i] = {x: Math.random()*W, y: -10, r: p.r, d: p.d};
        }
        else{
          if(Math.sin(angle) > 0){
            particles[i] = {x: -5, y: Math.random()*H, r: p.r, d: p.d};
          }
          else{
            particles[i] = {x: W+5, y: Math.random()*H, r: p.r, d: p.d};
          }
        }
      }
    }
  }
  setInterval(draw, 15);
}
  </script>
</body>
</html>

相關文章