使用canvas+html实现烟花/流星特效

先上代码,代码复制到txt文档然后重命名为html文件,用浏览器打开就可以看到。

<!DOCTYPE html> 
<html> 
<head> 
<meta charset="utf-8" /> 
<title>Canvas流星雨特效</canvas></title> 
<style> 
*{margin: 0; padding: 0;} 
#canvas 
{ 
background: #000; 
display: block; 
} 
</style> 
</head> 
<body> 
<canvas id="canvas">您的浏览器版本过低,请更换浏览器!</canvas> 
<script> 
var can=document.getElementById('canvas'); 
var ctx=can.getContext('2d'); 
var w=can.width=window.innerWidth; 
var h=can.height=window.innerHeight; 

var count=30; 
var drops=[]; 
window.οnresize=function() 
{ 
w=can.width=window.innerWidth; 
   h=can.height=window.innerHeight; 
}; 
function Drop(){} 
Drop.prototype={ 
init: function() 
{ 
this.x=random(0,w); 
this.y=0; 
this.r=1; 
this.color='#0ff'; 
this.vy=random(4,5); 
this.vr=1; 
this.a=1; 
this.va=0.96; 
this.l=random(h*0.8,h*0.9); 
}, 
draw:function() 
{ 
if(this.y>this.l) 
{ 
ctx.beginPath(); 
ctx.arc(this.x,this.y,this.r,0,2*Math.PI,false); 
ctx.strokeStyle='rgba(0,255,255,'+this.a+')'; 
ctx.stroke(); 
} 
else 
{ 
ctx.fillStyle=color(this.a); 
ctx.fillRect(this.x,this.y,2,10); 
} 
this.update(); 
}, 
update: function() 
{ 
if(this.y<this.l) 
{ 
this.y+=this.vy; 
} 
else 
{ 
if(this.a>0.03) 
{ 
this.r+=this.vr; 
if(this.r>50) 
{ 
this.a*=this.va; 
} 
} 
else 
{ 
this.init(); 
} 
} 
} 
} 
function move() 
{ 
ctx.fillStyle='rgba(0,0,0,.1)'; 
ctx.fillRect(0,0,w,h); 
for(var i=0;i<drops.length;i++) 
{ 
drops[i].draw(); 
} 
requestAnimationFrame(move); 
}; 
function setup() 
{ 
for(var i=0;i<count;i++) 
{ 
(function(j) 
{ 
setTimeout(function(){ 
var drop=new Drop(); 
drop.init(); 
drops.push(drop); 
},j*200); 
}(i)) 
} 
}; 
setup(); 
move(); 
function random(min,max) 
{ 
return Math.random()*(max-min)+min; 
}; 
function color(a) 
{ 
var r=Math.floor(Math.random()*255); 
var g=Math.floor(Math.random()*255); 
var b=Math.floor(Math.random()*255); 
return 'rgba('+r+','+g+','+b+','+a+')'; 
}; 
</script> 
</body> 
</html>

效果如下图所示:不过是动的哦
在这里插入图片描述

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值