用html写一个烟花特效
时间: 2023-09-28 17:07:44 浏览: 32
好的,我可以为您提供一个简单的HTML烟花特效代码,如下:
```
<!DOCTYPE html>
<html>
<head>
<title>Fireworks Effect</title>
<style>
.canvas {
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
z-index: -1;
}
</style>
</head>
<body>
<canvas class="canvas"></canvas>
<script>
(function() {
var canvas = document.querySelector('.canvas'),
ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
ctx.strokeStyle = '#ddd';
ctx.lineWidth = 1;
var fireworks = [];
function Firework() {
this.r = 2 + Math.random() * 2;
this.x = canvas.width / 2;
this.y = canvas.height / 2;
this.vx = Math.random() * 6 - 3;
this.vy = Math.random() * 6 - 3;
this.color = 'hsl(' + Math.floor(Math.random() * 360) + ', 50%, 50%)';
this.lastx = this.x;
this.lasty = this.y;
}
Firework.prototype.draw = function() {
ctx.beginPath();
ctx.moveTo(this.lastx, this.lasty);
ctx.lineTo(this.x, this.y);
ctx.strokeStyle = this.color;
ctx.stroke();
this.lastx = this.x;
this.lasty = this.y;
}
Firework.prototype.update = function() {
this.x += this.vx;
this.y += this.vy;
this.vy += 0.1;
if (this.y > canvas.height) {
for (var i = 0; i < 50; i++) {
var particle = new Particle(this.x, this.y);
fireworks.push(particle);
}
}
}
function Particle(x, y) {
this.x = x;
this.y = y;
this.vx = Math.random() * 6 - 3;
this.vy = Math.random() * 6 - 3;
this.r = 1 + Math.random() * 2;
this.color = 'hsl(' + Math.floor(Math.random() * 360) + ', 50%, 50%)';
}
Particle.prototype.draw = function() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2);
ctx.fillStyle = this.color;
ctx.fill();
}
Particle.prototype.update = function() {
this.x += this.vx;
this.y += this.vy;
this.vy += 0.1;
}
function animation() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
fireworks.forEach(function(firework, index) {
firework.draw();
firework.update();
if (firework.y > canvas.height) {
fireworks.splice(index, 1);
}
});
for (var i = 0; i < fireworks.length; i++) {
fireworks[i].draw();
fireworks[i].update();
}
window.requestAnimationFrame(animation);
}
window.requestAnimationFrame(animation);
setInterval(function() {
fireworks.push(new Firework());
}, 200);
})();
</script>
</body>
</html>
```
您可以在浏览器中打开此代码,查看效果。注意,代码应该在body标签内,Canvas标签的类要设置为"canvas",JS脚本要放在body标签的底部。希望以上代码能够帮到您!