实现效果:出现随机位置随机大小随机颜色的圆
body:<canvas id="bubble" ></canvas>
js:var canvas=document.getElementById("bubble");
var w=window.innerWidth;//canvas窗口和浏览器一样
var h=window.innerWidth;
canvas.width=w;
canvas.height=h;
window.οnresize=function(){//窗口大小发生变化
w=window.innerWidth;
h=window.innerWidth;
canvas.width=w;
canvas.height=h;
}
var cancon=canvas.getContext("2d");//2d平面
function Bubble(){};//构造类
function random(min,max){
return Math.random()*(max-min)+min;
}//random函数
var colorarry=["#e08031","#c7ceb2","#199475","#0b6e48","#044d22"]//4种颜色
Bubble.prototype= {//构造函数
init:function(){//初始化
this.x=random(0,w);
this.y=random(0,h);
this.r=random(0,3);
this.xr=random(-1,1);//x移动的范围
this.yr=random(-1,1);//y方向移动的范围
this.D=50;//在50px范围
this.color=colorarry[Math.floor(random(0,5))];//在四种颜色里随机取,颜色的搭配可以参考www.peise.net
},
draw:function(){
cancon.beginPath();//提笔重画
cancon.fillStyle=this.color;//圆形的颜色
cancon.arc(this.x,this.y,this.r,0,2*Math.PI);//圆形的参数
cancon.fill();//实心填满 stroke:不实心填满
},
update:function(){//更新小圆形泡泡
this.x+=this.xr;
this.y+=this.yr;
if(this.x-this.r<0 || this.x+this.r>w){
this.xr=-this.xr;
}//如果碰到边缘,则反弹回去,通过变化的值取反来操作
if(this.y-this.r<0 || this.y+this.r>h){
this.yr=-this.yr;
}
//算出鼠标的位置与当前小泡泡的x y轴距离
this.XD=(positionX-this.x)<0?-(positionX-this.x):(positionX-this.x);
this.YD=(positionY-this.y)<0?-(positionY-this.y):(positionY-this.y);
if(this.XD<this.D&&this.YD<this.D){
this.r+=1;
}
//如果距离小于定义的范围50,小圆形泡泡就膨胀
else if(this.r>4&&this.XD>this.D&&this.YD>this.D){
this.r-=1;
}
//如果距离大于定义值且半径大于4 ,就说明不在范围内,就缩小
this.draw();//更新完必须再画一次
}
};
var bubblearry=[];//定义一个数组存放泡泡
function create(){//生成泡泡的过程
var bubble=new Bubble();
bubble.init();
bubble.draw();
bubblearry.push(bubble);
}
for(var i=0;i<1000;i++){//生成1000个泡泡
create();
}
setInterval(function(){
cancon.clearRect(0,0,w,h);//清除上一个的,实现动态变化的效果
for(var b of bubblearry){
b.update();//遍历
}
},1000/60);//
var positionX,positionY;
//鼠标位置
canvas.οnmοusemοve=function( event){
var ev=ev || event;//浏览器兼容性
positionX=ev.clientX;
positionY=ev.clientY;
}