canvas蔚藍星空效果

admin發表於2018-07-06

分享一段程式碼例項,它利用canvas實現了蔚藍星空效果。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼執行程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style>
html, body {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
}
#starrynight {
  background: -webkit-linear-gradient(#00111e 30%, #033d5e);
  background: -moz-linear-gradient(#00111e 30%, #033d5e);
  background: -o-linear-gradient(#00111e 30%, #033d5e);
  background: linear-gradient(#00111e 30%, #033d5e);
  overflow: hidden;
}
</style>
</head>
<body>
<canvas id="starrynight"></canvas>
<script>
function drawing() {
  var c = document.getElementById('starrynight');
  var ctx = c.getContext('2d');
  var xMax = c.width = window.screen.availWidth;
  var yMax = c.height = window.screen.availHeight;
 
  var hmTimes = Math.round(xMax + yMax);
 
  for (var i = 0; i <= hmTimes; i++) {
    var randomX = Math.floor((Math.random() * xMax) + 1);
    var randomY = Math.floor((Math.random() * yMax) + 1);
    var randomSize = Math.floor((Math.random() * 2) + 1);
    var randomOpacityOne = Math.floor((Math.random() * 9) + 1);
    var randomOpacityTwo = Math.floor((Math.random() * 9) + 1);
    var randomHue = Math.floor((Math.random() * 360) + 1);
    if (randomSize > 1) {
      ctx.shadowBlur = Math.floor((Math.random() * 15) + 5);
      ctx.shadowColor = "white";
    }
    ctx.fillStyle = "hsla(" + randomHue + ", 30%, 80%, ." + randomOpacityOne + randomOpacityTwo + ")";
    ctx.fillRect(randomX, randomY, randomSize, randomSize);
  }
}
drawing();
</script>
</body>
</html>

相關文章