JS+CSS3点击粒子烟花动画js特效
以下是一个简单的JavaScript和CSS3实现的烟花弹动动画的示例代码:
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Click Confetti Animation</title>
<style>
body, html {
height: 100%;
margin: 0;
display: flex;
justify-content: center;
align-items: center;
background: #111;
}
.confetti {
position: absolute;
z-index: 1000;
pointer-events: none;
}
</style>
</head>
<body>
<button id="startConfetti">Click Me For Confetti!</button>
<canvas id="confetti-canvas" width="1770" height="700"></canvas>
<script>
const canvas = document.getElementById('confetti-canvas');
const ctx = canvas.getContext('2d');
const confetti = new Confetti({
parent: canvas,
gravity: 0.25,
velocity: 60,
size: 8,
width: canvas.width,
height: canvas.height,
x: 0.5,
y: 0.5
});
document.getElementById('startConfetti').addEventListener('click', () => {
confetti.start();
});
class Confetti {
constructor(options) {
this.parent = options.parent;
this.gravity = options.gravity;
this.velocity = options.velocity;
this.size = options.size;
this.width = options.width;
this.height = options.height;
this.x = options.x;
this.y = options.y;
this.running = false;
this.interval = null;
}
start() {
if (!this.running) {
this.running = true;
this.interval = setInterval(() => this.draw(), 1000 / 60);
}
}
stop() {
if (this.running) {
this.running = false;
clearInterval(this.interval);
}
}
draw() {
ctx.clearRect(0, 0, this.width, this.height);
ctx.fillStyle = 'rgba(255, 255, 255, 0.5)';
ctx.beginPath();
ctx.arc(this.x * this.width, this.y * this.height, this.size, 0, Math.PI * 2);
ctx.fill();
if (this.y >= 1) {
this.stop();
}
this.velocity += this.gravity;
this.y += this.velocity;
}
}
</script>
</body>
</html>
这段代码定义了一个简单的烟花类Confetti
,它可以在提供的canvas上绘制烟花并使其下落。在HTML中,有一个按钮用于触发烟花动画的开始,并且有一个canvas元素用于绘制烟花。CSS负责设置canvas的样式。
这个示例实现了基本的烟花弹动效果,但是你可以根据需要扩展Confetti
类来添加更多特性,比如不同形状的烟花、多种烟花颜色等。
评论已关闭