Sunday, January 20, 2013

Hi Guys! How are you? In previous post, I have mentioned so many time that HTML 5 gives big Competition to flash. But in real Competition is Flash VS HTML 5 Canvas. So I have decided to write some tutorials on HTML5 Canvas. Here Our first tutorial on HTML 5-Canvas.
HTML5 Canvas Tutorial On Creating Snowfall Effect

In our previous tutorials I have explained you Snowfall effect using CSS3, JavaScript. Today we will take that same concept but we will implement it in HTML 5 Canvas.
Read:
1)Make Your Blog Ready For Christmas Using ShowStrome.js
2)Amazing Snow Fall Effect Using Pure CSS3
HTML
<html>
 <head>
 </head>
 <body>
 </body>
<script type="text/javascript" src="snowfall.js"></script>
</html>  
You should put snowfall.js at the bottom of the page other wise the script won't work.
snowfall.js
(function(w,d,m,c) {
    //Create canvas tag on fly 
  var cnvs,ctx,Wt,Ht,maxF,flakes,b= d.getElementsByTagName('body')[0]; 
 cnvs = d.createElement(c);  
  b.appendChild(cnvs);
  //init canvas and set dimenctions 
  ctx=cnvs.getContext('2d');
  Wt=w.innerWidth;
  Ht=w.innerHeight;
  cnvs.width=Wt;
  cnvs.height=Ht;
  //Creating snow flakes 
 maxF= 100; //max flakes 
 flakes = [];
 for(var i = 0; i < maxF; i++)
 { 
  //pushing into flakes array
  flakes.push({
   x: m.random()*Wt, 
   y: m.random()*Ht, 
   r: m.random()*3, 
   d: m.random()*maxF
  })
 }
 function snowfall(){
  ctx.clearRect(0, 0, Wt, Ht);
  //drawing intitial snowflakes on canvas
  ctx.fillStyle = "#fff";
  ctx.beginPath();
  for(var i = 0; i < maxF; i++){
   var f = flakes[i];
   ctx.moveTo(f.x, f.y);
   ctx.arc(f.x, f.y, f.r, 0, m.PI*2, true);
  }
  ctx.fill();

  //moving snow flakes
  var angl=0;
  for(var i=0;i<maxF;i++){ 
   angl+=0.1;
   var f=flakes[i];
   f.x +=m.abs(m.sin(angl)) + 0.1 ;
   f.y += m.abs(m.cos(angl))*3;
   //resetting snowflakes when they are 
   //out of frame
   if(f.x > Wt || f.x < 0 || f.y > Ht){
    f.x=m.random()*Wt;
    f.y=-10;
   }
  }
 }
 //calling snowfall function every 30 sec
 setInterval(snowfall, 30);
}(window,document,Math,'canvas'));
Here we are using self calling JavaScript function. Just go thought the code you will understand whats going on.
That's it hope you like it.

0 comments :

Post a Comment