Saturday, 21 April 2018

How to Show Snow in the Background

How to Show Snow in the Background ?

 

HTML FILE

<html>
<head>
<title>Snowy Background</title>
</head>

<body>

    <canvas id="skyfall"></canvas>
   
</body>
</html>

 

CSS FILE

.body {  background-color: black;    }  

JAVASCRIPT FILE

window.onload = function()

{
 
  // get the canvas and context and store in vars
  var canvas = document.getElementById('skyfall');
  var ctx = canvas.getContext('2d');
 
  // set canvas dimensions to window height and width
  var W = window.innerWidth;
  var H = window.innerHeight;
  canvas.width = W;
  canvas.height = H;
 
  // generate the snowflakes and apply attributes
  var mf = 170; // max number of flakes
  var flakes = [];
 
  // loop through the empty flakes and apply attributes
for(var i = 0; i < mf; i++){
        flakes.push({
            x: Math.random()*W, //set width of flake to random nr between 0 and 1 * width of screen
            y: Math.random()*H, //set height of flake to random nr between 0 and 1 * height of screen
            r: Math.random()*5+2, //set radius between 2 and 5
            d: Math.random() + 1
        })
    }
 
  // draw flakes onto canvas
  function drawFlakes() {
    ctx.clearRect(0, 0, W, H); // clear rectangle
    ctx.fillStyle = "white";
    ctx.beginPath();
    for(var i = 0; i < mf; i++) {
      var f = flakes[i];
      ctx.moveTo(f.x, f.y);
      ctx.arc(f.x, f.y, f.r, 0, Math.PI * 2, true);
    }
    ctx.fill();
    moveFlakes();
  }
 
  // animate the flakes
  var angle = 0;
 
  // move flakes
  function moveFlakes() {
    angle += 0.01;
    for(var i = 0; i < mf; i++) {
     
      // store current flake
      var f = flakes[i];
     
      // update X and Y coordinate of each snowflake
      f.y += Math.pow(f.d, 2) + 1;
      f.x += Math.sin(angle) * 2;
     
      // if the snowflake reaches the bottom, send a new one to the top
      if(f.y > H) {
        flakes[i] = {
          x: Math.random() * W,
          y: 0,
          r: f.r,
          d: f.d
        };
      }
    }
  }
  setInterval(drawFlakes, 35);
}