随机泡泡放大缩小和随机泡泡位置改变
1.随机泡泡缩小放大
<!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>对象版随机泡泡</title>
<style>
#canvas {
border: 1px solid;
}
</style>
</head>
<body>
<canvas width="800" height="500" id="canvas"></canvas>
<script>
let canvas = document.getElementById("canvas");
let ctx = canvas.getContext("2d");
function random(start, end) {
if (!end) {
return Math.floor(Math.random() * start);
}
return Math.floor(Math.random() * (end - start + 1) + start);
}
function scaleNum(num) {
let random = (Math.random() * num).toFixed(1);
return random;
}
console.log(scaleNum(2));
class Paopao {
constructor() {
this.x = random(800);
this.y = random(500);
this.r = random(10, 50);
this.drect = 1;
this.scaleValue = 1;
this.op = 1;
this.speed = random(10,100);
this.color = `rgb(${random(256)},${random(256)},${random(256)})`;
}
draw() {
ctx.beginPath();
ctx.save();
ctx.translate(this.x,this.y);
if(this.scaleValue >=1.5 || this.scaleValue<=0){
this.drect *= -1;
}
this.scaleValue += 1/this.speed*this.drect;
ctx.scale(this.scaleValue, this.scaleValue);
if(this.op>=1||this.op<=0.1){
this.drect *= -1;
}
this.op += 1/this.speed*this.drect;
ctx.globalAlpha = this.scaleValue;
ctx.fillStyle = this.color;
ctx.arc(0, 0, this.r, 0, 2 * Math.PI);
ctx.fill();
ctx.restore();
}
}
let popAry = [];
for (let i = 0; i <= 50; i++) {
popAry.push(new Paopao());
}
setInterval(() => {
ctx.clearRect(0, 0, 800, 500);
for (let i = 0; i <= 30; i++) {
popAry[i].draw();
}
}, 50);
</script>
</body>
</html>
2.随机泡泡位置改变
<!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>随机泡泡</title>
<style>
#canvas {
border: 1px solid;
}
</style>
</head>
<body>
<canvas width="1000" height="800" id="canvas"></canvas>
<script>
let canvas = document.getElementById("canvas");
let ctx = canvas.getContext("2d");
function color() {
let r = Math.floor(Math.random() * 256);
let g = Math.floor(Math.random() * 256);
let b = Math.floor(Math.random() * 256);
let a = Math.random().toFixed(1);
return "rgb" + "(" + r + "," + g + "," + b + "," + a + ")";
}
console.log(color());
function circular(min, max) {
return Math.floor(Math.random() * (max + 1 - min) + min);
}
function scaleNum(num) {
return (Math.random() * num).toFixed(1);
}
setInterval(() => {
ctx.clearRect(0,0,1000,800);
for (let i = 0; i <= 50; i++) {
ctx.save();
ctx.beginPath();
ctx.translate(circular(50, 950),circular(50, 950));
ctx.fillStyle = color();
ctx.arc(0, 0, circular(10, 50), 0, 2 * Math.PI);
ctx.fill();
ctx.restore();
}
}, 1000);
</script>
</body>
</html>