canvas绘制小球渐隐渐现

快乐打工仔 分类:实例代码

canvas绘制小球渐隐渐现属于前端实例代码,有关更多实例代码大家可以查看

分享一段代码实例,它实现了利用canvas绘制渐隐渐现小球的功能。

代码实例如下:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.pipipi.net/" />
<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>

canvas绘制小球渐隐渐现,这样的场景在实际项目中还是用的比较多的,关于canvas绘制小球渐隐渐现就介绍到这了。

回复

我来回复
  • 暂无回复内容