canvas實現的雪花飄落效果程式碼例項

admin發表於2017-02-17

分享一段程式碼例項,它利用canvas實現了雪花飄落效果。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style>
* {
  padding: 0;
  margin: 0;
}
#box {
  margin: 0 auto;
  width: 600px;
  position: relative;
}
#fcan {
  position: absolute;
  top: 0;
  z-index: 100;
}
#bg {
  position: absolute;
  top: 0;
}
#bg img {
  width: 600px;
  height: 400px;
}
</style>
</head>
<body>
<div id="box">
  <canvas id="fcan" width="600" height="400" ></canvas>
</div>
<script>
var rains = [];
var can = document.getElementById('fcan');
var ct = can.getContext('2d');
init();
 
setInterval(function() {
  rainsNum();
  ct.clearRect(0, 0, 600, 400);
  init();
  dropDown();
}, 50);
//初始化
function init() {
  ct.rect(0, 0, 600, 400);
  ct.fillStyle = '#000';
  ct.fill();
}
//產生隨機雨滴
function createRain() {
  var ix = Math.random() * 600;
  var iy = Math.random() * 50;
  var ir = Math.random() * 4;
  var ivy = Math.random() * 5 + 2;
  var rain = {
    x: ix,
    y: iy,
    r: ir,
    vy: ivy,
    g: 8
  };
  rains.push(rain);
}
 
function rainsNum() {
  createRain();
}
//落下
function dropDown() {
  var len = rains.length;
  for (var i = 0; i < len; i++) {
    drawRain(rains<i>.x, rains<i>.y, rains<i>.r, ct);
    rains<i>.v += rains<i>.g;
    rains<i>.y += rains<i>.vy;
  }
}
//畫雪花
function drawRain(x, y, r, obj) {
  obj.fillStyle = '#fff';
  obj.beginPath();
  obj.arc(x, y, r, 0, Math.PI * 2, true);
  obj.closePath();
  obj.fill();
}
</script>
</body>
</html>

相關文章