canvas繪製小球漸隱漸現

admin發表於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%;
  width:100%;
}
#cvs{
  position:absolute;
  top:0;
  display:block;
  background-color:#000;
}
</style>
<script src="http://libs.baidu.com/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<canvas id = "cvs" width="1700" height="800"></canvas>
<script type="text/javascript">
var canvas = $("#cvs");
var ctx = canvas.get(0).getContext("2d");
canvas.attr("width", $(window).get(0).innerWidth);
canvas.attr("height", $(window).get(0).innerHeight);
$(window).resize(resizeCanvas);
 
function resizeCanvas() {
  canvas.attr("width", $(window).get(0).innerWidth);
  canvas.attr("height", $(window).get(0).innerHeight);
};
resizeCanvas();
var canvasWidth = canvas.width();
var canvasHeight = canvas.height();
var Shape = function(p, x, y, radius) {
  this.p = p;
  this.x = x;
  this.y = y;
  this.radius = radius;
};
var shapes = new Array();
for (var i = 0; i < 20; i++) {
  var p = 0.7;
  var x = Math.random() * canvasWidth;
  var y = Math.random() * canvasHeight / 3 + canvasHeight / 3;
  var radius = Math.random() * 10;
  shapes.push(new Shape(p, x, y, radius));
};
var playAnimation = true;
function animate() {
  for (i = 0; i < 20; i++) {
    var a = shapes[i];
    a.p -= 0.005;
    a.radius += .5;
    ctx.beginPath();
    ctx.fillStyle = 'rgba(0, 0, 0,0.1)';
    ctx.shadowBlur = 50;
    ctx.shadowColor = 'rgba(178, 0, 255, ' + a.p + ')';
    ctx.arc(a.x, a.y, a.radius, 0, Math.PI * 2, false);
    ctx.fill();
    if (a.p < 0) {
      ctx.clearRect(0, 0, canvasWidth, canvasHeight);
      a.x = Math.random() * canvasWidth;
      a.y = Math.random() * canvasHeight / 3 + canvasHeight / 3;
      a.radius = Math.random() * 10;
      a.p = 0.7;
    };
  }
  if (playAnimation) {
    setTimeout(animate, 33);
  };
};
animate();
</script>
</body>
</html>

相關文章