效果如下:
大家可以去以下网址体验:
Document功能:鼠标移入画布,会随机生成随机个数的随机颜色随机大小的气泡向随机的X方向和随机的Y方向移动随机的距离
思路:
1、为节约时间,用了underscore插件中的随机random方法和遍历each方法
2、创建了Ball类用来设计气泡特征;
3、创建balls列表(数组)来存储鼠标移动时间中生成的Ball类实例对象;
4、用时钟刷新canvas画布实现动画效果;
源代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
canvas:nth-of-type(1){
position: relative;
left: 800px;
top: -500px;
}
</style>
<script src="tools/underscore.js"></script>
<script>
window.onload=function(){
var huaban2=document.querySelector(".canvas2");
var bicaso2=huaban2.getContext("2d");
var timer2=null;
var inFlag=false;
var balls=[];
var speed=0.03;
huaban2.onmouseover=function(){
inFlag=true;
}
huaban2.onmouseleave=function(){
inFlag=false;
}
huaban2.onmousemove=function(event){
if(inFlag){
if(_.random(1000)>=500){
var ball1=new Ball(event.pageX-800,
event.pageY-17,
_.random(5,25),
"#"+_.random(255).toString(16)+_.random(255).toString(16)+_.random(255).toString(16),
_.random(-150,150),
_.random(-150,150))
balls[balls.length]=ball1;
}
}
}
function Ball(x,y,r,color,endx,endy){
this.color=color;
this.size=r;
this.nowX=x;
this.nowY=y;
this.endX=endx;
this.endY=endy;
}
function ballMove(balls){
}
timer2=setInterval(function(){
bicaso2.clearRect(0,0,500,800);
_.each(balls,function(value,key,list){
bicaso2.beginPath();
if(value){
if(value.endX){
value.nowX=value.nowX+value.endX*speed;
value.endX=value.endX*(1-speed);
if(value.endX<10 && value.endX>-10){value.endX=0}
}
if(value.endY){
value.nowY=value.nowY+value.endY*speed;
value.endY=value.endY*(1-speed);
if(value.endY<10 && value.endY>-10){value.endY=0}
}
bicaso2.fillStyle=value.color;
bicaso2.arc(value.nowX,value.nowY,value.size,0,2*Math.PI,false)
bicaso2.fill();
}
bicaso2.closePath();
});
for(var i=0;i<balls.length;i++){
if(balls[i].endX==0){
balls.splice(i,1);
}
}
},20)
function zhengfuhao (){
var x=_.random(-1,1);
if(x>=0){
return 1;
}else{
return -1;
}
}
}
</script>
</head>
<body>
<canvas class="canvas2" width="500" height="800">您的浏览器太旧了,不支持canvas</canvas><br>
</body>
</html>