<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<!-- <style>
</style> -->
</head>
<body>
<canvas id="myCanvas"></canvas>
<script>
var myCanvas = document.getElementById("myCanvas");
var canvasWid = 600;
var canvasHei = 400;
var circleR = 15;
myCanvas.width = canvasWid;
myCanvas.height = canvasHei;
var ctx = myCanvas.getContext("2d");
var circleList = [];
class Circle {
constructor(x, y, r) {
let xRange = canvasWid - circleR * 2;
let yRange = canvasHei - circleR * 2;
this.x = circleR + Math.floor(Math.random() * xRange);
this.y = circleR + Math.floor(Math.random() * yRange);
this.r = circleR;
let dx = 2 + Math.ceil(Math.random() * 3);
let dy = 2 + Math.ceil(Math.random() * 3);
this.dx = Math.random() > 0.5 ? dx : -dx;
this.dy = Math.random() > 0.5 ? dy : -dy;
this.color = this.getRandomColor();
circleList.push(this);
this.render();
console.log("this.x", this.x);
console.log("this.y", this.y);
}
getRandomColor() {
return `rgba(${Math.round(Math.random() * 255)},${Math.round(
Math.random() * 255
)},${Math.round(Math.random() * 255)}, ${Math.random().toFixed(2)})`;
}
update() {
let x = this.x + this.dx;
let y = this.y + this.dy;
if (x >= canvasWid - circleR) {
this.x = canvasWid - circleR;
this.dx = this.dx > 0 ? -this.dx : this.dx;
} else if (x < circleR) {
this.x = circleR;
this.dx = this.dx < 0 ? -this.dx : this.dx;
} else {
this.x = x;
}
if (y >= canvasHei - circleR) {
this.y = canvasHei - circleR;
this.dy = this.dy > 0 ? -this.dy : this.dy;
} else if (this.y < circleR) {
this.y = circleR;
this.dy = this.dy < 0 ? -this.dy : this.dy;
} else {
this.y = y;
}
}
render() {
ctx.beginPath();
ctx.globalAlpha = 1;
ctx.fillStyle = this.color;
//注意:画圆时, x,y 为圆心坐标
ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2, false);
ctx.fill();
ctx.closePath();
}
}
for (let i = 0; i < 30; i++) {
new Circle();
}
setInterval(function () {
ctx.clearRect(0, 0, canvasWid, canvasHei);
circleList.forEach((circle) => {
circle.update();
circle.render();
});
}, 30);
</script>
</body>
</html>