白话
挺简单实现的一个小小的js小东西,注释写的很详细了。还是直接看代码吧

大白话
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>canvas气泡</title>
</head>
<body>
<canvas>
</canvas>
</body>
<script>
class Circle {
constructor(color, radius, velocity_x, velocity_y, x, y) {
this.color = color;//颜色
this.radius = radius;//圆的半径
this.velocity_x = velocity_x;//x方向上的速度
this.velocity_y = velocity_y;//y方向上的速度
// this.angle = angle;这是改进,第一种思路是利用角度来进行气泡球体的移动,关于距离的增加利用三角函数进行计算。
// 相关计算下面有
this.x = x;//气泡球的位置
this.y = y;
}
draw(ctx) {
ctx.beginPath();
//路径开始,使其可以开始绘制气泡
ctx.arc(
this.x,
this.y,
//初始位置
this.radius,
//半径
0,
//开始角度
2 * Math.PI);
//结束角度
//绘制气泡,aka就是一个圆。
ctx.closePath();
ctx.fillStyle = this.color;
ctx.fill();
//填充颜色。
}
}
let arr = [];
//气泡的数量
const CNT = 200;
let centerX = 0, centerY = 0;
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
centerX = canvas.width / 2;
centerY = canvas.height / 2;
for (let i = 0; i < CNT; ++i) {
//随机生成200个气泡,颜色,,半径,速度,均为随机值。
let c = new Circle(
'rgba(' + 255 * Math.random() + ',' + 255 * Math.random() + ',' + 255 * Math.random() + ',' + Math.random() + ')',
10 * Math.random() + 1,
5 * (Math.random() * 2 - 1),
5 * (Math.random() * 2 - 1),
centerX,
centerY
);
arr.push(c);
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);//每次绘制前,先清除目前屏幕上的所以内容,以达到移动显示的目的。
for (let i = 0; i < CNT; ++i) {
// arr[i].x += arr[i].velocity * Math.cos(arr[i].angle);
// arr[i].y += arr[i].velocity * Math.sin(arr[i].angle);
arr[i].x += arr[i].velocity_x;
arr[i].y += arr[i].velocity_y;
//碰撞检测,分两种情况,碰到上下边界 就y轴方向反向,碰到左右边界,就x轴速度方向反向
if (arr[i].y - arr[i].radius <= 0 || arr[i].y + arr[i].radius >= canvas.height) {
arr[i].velocity_y *= -1;
}
if (arr[i].x - arr[i].radius <= 0 || arr[i].x + arr[i].radius >= canvas.width) {
arr[i].velocity_x *= -1;
}
arr[i].draw(ctx);
}
setTimeout(draw, 30);//每30毫秒就执行一次,展现出移动的效果。
}
console.log(arr);
draw();
</script>
</html>
碎碎念的大白话
挺简单的一个东西,没啥可说的。此时和那个准备出国的害人精朋友产生了一样迷茫的想法,可是出路究竟在哪里呢。我们无从寻找,只能继续“go 皮卡丘”,激励着彼此,Wish u all the best.
Comments | NOTHING