canvas实现跳动小球
![](https://img2020.cnblogs.com/blog/2029843/202009/2029843-20200908132714064-476731791.png)
html部分
<!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>
.root {
width: 100%;
height: 600px;
background-color: black;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
}
.root canvas {
background-color: rgb(0, 0, 0);
}
</style>
</head>
<body>
<div class="root">
<canvas id='canvas' width="1000" height="500"></canvas>
</div>
<script src="./canvas_3.js"></script>
</body>
</html>
js部分
class Animate {
constructor(id) {
this.id = id
this.balls = []
this.canvas = document.getElementById(this.id)
this.context = this.canvas.getContext('2d')
this._init_()
}
_init_() {
for (let i = 0; i < 400; i++) {
let x = Math.floor(Math.random() * (600 - 30)) + 30
let y = Math.floor(Math.random() * (400 - 20)) + 20
let dx = Math.floor(Math.random() * (4 - 2)) + 2
let dy = Math.floor(Math.random() * (4 - 2)) + 2
let radius = Math.floor(Math.random() * (20 - 10)) + 10
let color = `rgb(${Math.floor(Math.random() * (255 - 0) + 0)}, ${Math.floor(Math.random() * (255 - 0) + 0)}, ${Math.floor(Math.random() * (255 - 0) + 0)})`
this.balls.push(new Ball(x, y, dx, dy, radius, color))
}
this.animate()
}
animate() {
requestAnimationFrame(this.animate.bind(this))
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height)
for (let i = 0; i < 400; i++) {
this.balls[i].move()
}
}
}
class Ball {
constructor(x, y, dx, dy, radius, color) {
this.x = x
this.y = y
this.dx = dx
this.dy = dy
this.radius = radius
this.color = color
this.canvas = document.getElementById('canvas')
this.context = this.canvas.getContext('2d')
this.drawBall()
}
drawBall() {
this.context.beginPath();
this.context.arc(this.x, this.y, this.radius, Math.PI / 180 * 0, Math.PI / 180 * 2, true);
this.context.fillStyle = this.color;
this.context.fill()
}
move() {
if (this.x + this.radius > this.canvas.width || this.x - this.radius < 0) {
this.dx = -this.dx
}
if (this.y + this.radius > this.canvas.height || this.y - this.radius < 0) {
this.dy = -this.dy
}
this.x += this.dx
this.y += this.dy
this.drawBall()
}
}
new Animate('canvas')