代码部分:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>canvas气泡</title>
<style>
.container{
background-color: rgba(0, 0, 0, 0.911);
}
body{
padding: 0px;
margin: 0px;
}
</style>
</head>
<body>
<div class="container">
<canvas></canvas>
</div>
</body>
<script>
/**
* 类circle
*/
class circle{
/**
* 构造器
* @param color 颜色
* @param radius 半径
* @param v 速度
* @param angle 初始移动角度
* @param x 当前x坐标
* @param y 当前y坐标
*/
constructor(color,radius,v,angle,x,y){
this.color = color;
this.radius = radius;
this.v = v;
this.angle = angle;
this.x = x;
this.y = y;
}
/**
* 绘制圆
* @param ctx 绘制上下文
*/
draw(ctx){
//开始绘制路径
ctx.beginPath();
//绘制圆
ctx.arc(this.x,this.y,this.radius,
0,2*Math.PI);
//关闭绘制路径
ctx.closePath();
//设置fill颜色
ctx.fillStyle = this.color;
//fill
ctx.fill();
}
}
//圆对象数组
let arr = []; //new Array();
//圆数量
const CNT = 200;
//绘制区域中心点
let X,Y;
//canvas 元素
const canvas = document.querySelector('canvas');
//绘制上下文
const ctx = canvas.getContext('2d');
//设置canvas满屏
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
//设置中心点
X = canvas.width;
Y = canvas.height;
//实例化200个圆
for(let i=0;i<CNT;i++){
let c = new circle(
// 构建随机色
'rgba(' + 255*Math.random() + ','
+ 255*Math.random() + ','
+ 255*Math.random() + ','
+ Math.random()
+ ')',
//随机半径1-15
14*Math.random()+1,
//随机速度 1-5
4*Math.random() + 1,
//随机方向0-360度
360 * Math.random(),
X*Math.random(),
Y*Math.random()
);
arr.push(c);
}
/**
* 绘制
*/
function draw(){
//清除绘图上下文
ctx.clearRect(0,0,canvas.width,canvas.height);
for(let i=0;i<CNT;i++){
//移动x坐标
arr[i].x += arr[i].v * Math.cos(arr[i].angle);
//移动y坐标
arr[i].y += arr[i].v * Math.sin(arr[i].angle);
if(arr[i].x>window.innerWidth || arr[i].y>window.innerHeight || arr[i].x<0 || arr[i].y<0){
arr[i].x = window.innerWidth*Math.random();
arr[i].y = window.innerHeight*Math.random();
}
//调用圆的绘制方法
arr[i].draw(ctx);
}
//延迟50ms继续绘制
setTimeout(draw,50);
}
//调用绘制
draw();
</script>
</html>
该画布大小设置为整个浏览器的大小,如果需要设置不同的画布大小,需要修改canvas.height与canvas.width的大小以及arr[i].x与arr[i].y为设置画布大小*Math.random()