烟花绽放代码html
时间: 2023-12-08 15:02:49 浏览: 99
以下是一个简单的HTML5 Canvas烟花绽放特效的代码示例:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>烟花绽放特效</title>
<style>
canvas {
background-color: black;
}
</style>
</head>
<body>
<canvas id="myCanvas"></canvas>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var particles = [];
var particleCount = 100;
var particleSpeed = 2;
var particleRadius = 3;
var particleColor = "white";
var particleExplosionSpeed = 6;
var particleGravity = 0.05;
function Particle(x, y) {
this.x = x;
this.y = y;
this.vx = (Math.random() - 0.5) * particleSpeed;
this.vy = (Math.random() - 0.5) * particleSpeed;
this.radius = particleRadius;
this.color = particleColor;
this.alpha = 1;
this.gravity = particleGravity;
this.explosionSpeed = particleExplosionSpeed;
}
Particle.prototype.draw = function() {
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.closePath();
};
Particle.prototype.update = function() {
this.x += this.vx;
this.y += this.vy;
this.vy += this.gravity;
this.alpha -= 0.01;
this.radius -= 0.02;
};
Particle.prototype.explode = function() {
for (var i = 0; i < particleCount; i++) {
var particle = new Particle(this.x, this.y);
var angle = Math.random() * Math.PI * 2;
var speed = Math.random() * this.explosionSpeed;
particle.vx = Math.cos(angle) * speed;
particle.vy = Math.sin(angle) * speed;
particles.push(particle);
}
};
function animate() {
requestAnimationFrame(animate);
ctx.clearRect(0, 0, canvas.width, canvas.height);
if (particles.length === 0) {
var particle = new Particle(canvas.width / 2, canvas.height / 2);
particle.explode();
particles.push(particle);
}
for (var i = 0; i < particles.length; i++) {
var particle = particles[i];
if (particle.alpha > 0) {
particle.draw();
particle.update();
} else {
particles.splice(i, 1);
}
}
}
animate();
</script>
</body>
</html>
```
阅读全文