附上代码
HTML
<!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>
* {
padding: 0;
margin: 0;
}
body {
width: 100vw;
height: 100vh;
overflow: hidden;
}
#canvas {
background-color: #000000;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
</body>
<script src="./index.js"></script>
</html>
Javascript
/** @type {HTMLCanvasElement} */
const can = document.getElementById("canvas");
can.width = window.innerWidth;
can.height = window.innerHeight;
const ctx = can.getContext("2d");
// 定义小球
class Ball {
constructor(x, y, dirX, dirY, color) {
// 起始位置
this.x = x;
this.y = y;
// 爆炸方向
this.dirX = dirX;
this.dirY = dirY;
// 大小
this.radius = 3;
// 透明度
this.opacity = 4;
// 颜色
this.color = color;
}
// 绘画小球
draw() {
ctx.beginPath();
ctx.fillStyle = this.color;
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
ctx.fill();
ctx.closePath();
}
// 绘制路线
update() {
this.dirX *= 0.99;
this.dirY *= 0.99;
this.dirY += 0.1;
this.x += this.dirX;
this.y += this.dirY;
this.opacity -= 0.01;
this.draw();
}
}
const balls = [];
function animate() {
ctx.fillStyle = "rgba(0,0,0,0.05)";
ctx.fillRect(0, 0, can.width, can.height);
for (let index = 0; index < balls.length; index++) {
const element = balls[index];
element.update();
// 透明度小于0.1就删除
if (element.opacity < 0.1) {
balls.splice(index, 1);
}
}
// 重复执行动画
requestAnimationFrame(animate);
}
animate();
can.addEventListener("click", (e) => {
// 小球数量
const nums = 400;
// 每一个偏移弧度
const hd = (Math.PI * 2) / nums;
// 循环创建小球和爆炸区间
for (let index = 0; index < nums; index++) {
balls.push(
new Ball(
// 位置
e.x,
e.y,
// 爆炸方向
Math.cos(hd * index) * (Math.random() * 20),
Math.sin(hd * index) * (Math.random() * 20),
// 颜色
`hsl(${Math.random() * 360},50%,50%)`
)
);
}
});
Canvas 学习作业完成