canvas漫天飛雪效果程式碼

antzone發表於2018-05-20

分享一段程式碼例項,它利用canvas實現了滿天飛雪效果。

程式碼例項如下:

[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;
}
html, body {
  height: 100%;
}
#myCanvas {
  background-color: #87CEEB;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="1000" height="600"></canvas>
<script type="text/javascript">
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var practicles = [];
for (var count = 0; count < 500; count++) { //迴圈生成500粒
  practicles.push({
    x: Math.random() * (window.innerWidth),
    y: Math.random() * (window.innerHeight),
    vx: Math.random() - 0.5,
    vy: Math.random() + 0.5,
    size: Math.random() * 3 + 1,
    color: "#FFF"
  })
}
function timeUpdate() {
  context.clearRect(0, 0, window.innerWidth, window.innerHeight); //清除畫布區域
  var practicle;
  for (var count = 0; count < 500; count++) {
    var practicle = practicles[count];
    practicle.x += practicles[count].vx;
    practicle.y += practicles[count].vy;
    if (practicle.x < 0) {
      practicle.x = window.innerWidth
    }
    if (practicle.x > window.innerWidth) {
      practicle.x = 0
    }
    if (practicle.y > window.innerHeight) {
      practicle.y = 0
    }
    context.beginPath();
    context.arc(practicle.x, practicle.y, practicle.size, 0, Math.PI * 2)
    context.closePath();
    context.fillStyle = practicle.color;
    context.fill();
  }
}
setInterval(timeUpdate, 40);
</script>
</body>
</html>

相關文章