编程实践:以class的方式实现小球运动动画
实现效果
1. 可以设置初始化,屏幕内的小球个数
2. 小球随机运动,动画效果
3. 小球颜色值随机生成:https://www.cnblogs.com/xiaobaiv/p/9503653.html
4. 鼠标轨迹跟随
5. 小球的碰撞检测,撞到墙壁反弹
6. 在四边生成的小球能完全显示
代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>动态气泡球</title>
<style>
body {
margin: 0;
}
.bubble {
background-color: black;
display: block;
}
</style>
</head>
<body>
<canvas class="bubble"></canvas>
<script>
//气泡球class
class Bubble {
constructor(x, y) {
if (0 === arguments.length) {
this.init()
}
else {
this.init(x, y)
}
}
init(x, y) {//初始化,overload重载
if (0 === arguments.length) {
this.x = this.random(0, w)
this.y = this.random(0, h)
}
else {
this.x = x
this.y = y
}
this.r = this.random(3, 12)//半径
this.color = ("#" + Math.floor(Math.random() * 0xffffff).toString(16))//随机颜色值
this.vx = this.random(-1, 1)//坐标移动的offset
this.vy = this.random(-1, 1)
//在四边生成的小球能完全显示
this.x = this.x - this.r < 0 ? this.r : this.x
this.x = this.x + this.r > w ? w - this.r : this.x
this.y = this.y - this.r < 0 ? this.r : this.y
this.y = this.y + this.r > h ? h - this.r : this.y
}
random(min, max) {//生成[min, max]之间的随机数. Math.random()取值[0,1]
return Math.random() * (max - min) + min
}
move() {//移动
this.x += this.vx
this.y += this.vy
}
collisionRebound() {//碰边反弹
if (this.x - this.r < 0 || this.x + this.r > w) {
this.vx = -this.vx
}
if (this.y - this.r < 0 || this.y + this.r > h) {
this.vy = -this.vy
}
}
draw() {//绘制
conT.beginPath()//开始一条路径,或重置当前的路径
conT.fillStyle = this.color
conT.arc(this.x, this.y, this.r, 0, 2 * Math.PI)//创建路径.圆心坐标,起始角和结束角
conT.fill()//绘制圆弧路径
}
}
{//业务代码
var canvas = document.getElementsByClassName('bubble')[0]
var conT = canvas.getContext('2d')//2d绘图环境
//获取浏览器宽高
var w = window.innerWidth
var h = window.innerHeight
canvas.width = w
canvas.height = h
var Bubbles = []//存放气泡球对象
var bubbleCount = 200
window.onresize = () => {//根据浏览器宽高设置canvas的宽高
w = window.innerWidth
h = window.innerHeight
canvas.width = w
canvas.height = h
}
//鼠标轨迹跟随
canvas.addEventListener("mousemove", (event) => {
var len = Bubbles.length
Bubbles[len] = new Bubble(event.pageX, event.pageY)
}, false)
for (let i = 0; i < bubbleCount; i++) {//生成气泡球200个
Bubbles[i] = new Bubble()
}
window.setInterval(function () {
conT.clearRect(0, 0, w, h)//清空矩形区域,视觉上无法感知到。清除旧球
for (var item of Bubbles) {
item.move()
item.collisionRebound()
item.draw()
}
}, 1000 / 30)//1秒30帧 1000 / 30
}
</script>
</body>
</html>
github源码地址:https://github.com/YanYuXieYang/WebProject/tree/main/crazy_ball_animation