用css html JavaScript 写一个烟花绽放的代码要求在500*500px的盒子中
时间: 2023-06-13 20:08:35 浏览: 122
JavaScript实现烟花绽放动画效果
下面是一个简单的烟花绽放效果的代码,使用了 HTML、CSS 和 JavaScript:
HTML:
```html
<div class="firework-container">
<canvas id="canvas" width="500" height="500"></canvas>
</div>
```
CSS:
```css
.firework-container {
width: 500px;
height: 500px;
position: relative;
background-color: black;
}
#canvas {
position: absolute;
top: 0;
left: 0;
}
```
JavaScript:
```javascript
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const particles = [];
const colors = ['#f44336', '#e91e63', '#9c27b0', '#673ab7', '#3f51b5', '#2196f3', '#03a9f4', '#00bcd4', '#009688', '#4CAF50', '#8BC34A', '#CDDC39', '#FFEB3B', '#FFC107', '#FF9800', '#FF5722'];
function random(min, max) {
return Math.random() * (max - min) + min;
}
function Particle(x, y, radius, color, velocity) {
this.x = x;
this.y = y;
this.radius = radius;
this.color = color;
this.velocity = velocity;
this.alpha = 1;
}
Particle.prototype.draw = function() {
ctx.save();
ctx.globalAlpha = this.alpha;
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
ctx.fillStyle = this.color;
ctx.fill();
ctx.restore();
};
Particle.prototype.update = function() {
this.x += this.velocity.x;
this.y += this.velocity.y;
this.velocity.x *= 0.99;
this.velocity.y *= 0.99;
this.alpha -= 0.01;
};
function createFirework() {
const firework = {
x: random(0, canvas.width),
y: canvas.height,
color: colors[Math.floor(Math.random() * colors.length)],
particles: []
};
for (let i = 0; i < 50; i++) {
const angle = random(0, Math.PI * 2);
const velocity = {
x: Math.sin(angle) * random(5, 15),
y: Math.cos(angle) * random(5, 15)
};
firework.particles.push(new Particle(firework.x, firework.y, 3, firework.color, velocity));
}
particles.push(firework);
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (let i = 0; i < particles.length; i++) {
const firework = particles[i];
for (let j = 0; j < firework.particles.length; j++) {
const particle = firework.particles[j];
particle.draw();
particle.update();
}
if (firework.particles[0].alpha <= 0) {
particles.splice(i, 1);
}
}
requestAnimationFrame(draw);
}
setInterval(createFirework, 1000);
draw();
```
这段代码会在指定大小的盒子内显示一个黑色背景,并在其中绘制烟花绽放的效果。每隔一秒钟,会创建一个新的烟花,每个烟花会有多个颜色随机的粒子,这些粒子会向不同方向发射,并且逐渐消失。整个效果使用 `requestAnimationFrame` 不断地更新画布,从而实现动态效果。
阅读全文