特效描述:html5 canvas 随机生成 小球冒泡动画。html5 canvas 随机生成 小球冒泡动画
代码结构
1. HTML代码
var canvas=document.createElement("canvas")
var ctx=canvas.getContext("2d")
var w=window.innerWidth;
var h=window.innerHeight;
init()
function init(){
canvas.width=w;
canvas.height=h;
document.body.appendChild(canvas)
setInterval(loop,30)
}
function Yuan(x,y,color){
this.x=x;
this.y=y;
this.xval=0;
this.yval=-9;
this.gro=0.1;
this.color=color;
this.yuan=function(){
ctx.beginPath()
ctx.fillStyle=this.color
ctx.arc(this.x,this.y,10,0,Math.PI*2)
ctx.fill()
ctx.closePath()
}
this.weizi=function(){
this.yval+=this.gro
this.x+=this.xval
this.y+=this.yval
}
}
var arr=[];
function loop(){
var x=w*0.5
var y=h*0.8
ctx.clearRect(0,0,w,h)
var col=sColor()
var yuan=new Yuan(x,y,col)
yuan.xval=Math.random()*4
arr.push(yuan)
//console.log(arr.length)
for(var i in arr){
arr[i].yuan()
arr[i].weizi()
}
if(arr.length>500){
arr.shift()
}
}
function sColor(){
return "rgba("+parseInt(Math.random()*255)+","+parseInt(Math.random()*255)+","+parseInt(Math.random()*255)+",1)"
}