canvas實現的雪花飄落效果

admin發表於2017-02-13
分享一段程式碼例項,它利用canvas實現了雪花飄落效果。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style type="text/css">
body{
  font-family:Arial,Helvetica,sans-serif;
  font-size:100%;
  line-height:1em;
  background:#003366;
}
                 
</style>
</head>
<body>
<canvas id = "canvas" style="position:absolute;"></canvas>
<script>
var X = window.innerWidth-50;
var Y = window.innerHeight-50;
var angle = 0;
var mp = 30;
var point = new Array();
for(var i=0;i<=mp;i++){
  point.push({
    x:Math.random()*X,
        y:Math.random()*Y,
    r:Math.random()*6+1,
        d:Math.random()*30
  });
}
function init(){
  var c = document.getElementById('canvas');
  canvas.width = X;
  canvas.height = Y;
  var ctx = c.getContext('2d');
  ctx.clearRect(0,0,X,Y);
  ctx.fillStyle = 'rgba(255, 255, 255, 0.8)';
  ctx.beginPath();
  for(var i = 0;i<=mp;i++){
    ctx.moveTo(point<i>.x,point<i>.y);
        ctx.arc(point<i>.x,point<i>.y,point<i>.r,0,2*Math.PI,true);
  }
  ctx.fill();
  update();
}
function update() {
  angle += 0.01;
  for (var i = 0; i <=mp; i++) {
    var p = point<i>;
        p.y += Math.cos(angle + p.d) + 1 + p.r / 2;
        p.x += Math.sin(angle) * 2;
        if (p.x > X + 5 || p.x < -5 || p.y > Y) {
          point<i> = {
            x: Math.random() * X,
                y: -10,
                r: p.r,
                d:p.d
          }
        }
  }
}
setInterval(init,33);
$('h1').fadeIn(3000);
$('.slide3').hide();
$('.slide2').hide();
$('.slide1').mousemove(function(){
}).mouseout(function(){
  $(this).css('border','none');                                
})
$('.slide1-ul a').mousemove(function(){
  $(this).css('border-bottom','1px solid #e4e4e4');
}).mouseout(function(){
  $(this).css('border-bottom','none');
}).fadeIn(5000);
$('.slide-right').click(function(){
  $('.slide1').css({'-webkit-transform-style':'preserve-3d','-webkit-animation':'spin 3s'});
});
</script>
</body>
</html>

相關文章