HTMLcanvas标签烟花效果
时间: 2023-10-14 16:30:53 浏览: 43
可以使用HTML5的Canvas标签来实现烟花效果。以下是一个简单的实现,你可以根据自己的需求进行调整:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>烟花效果</title>
<style type="text/css">
canvas {
background-color: #000;
display: block;
margin: 0 auto;
}
</style>
</head>
<body>
<canvas id="fireworks" width="800" height="600"></canvas>
<script type="text/javascript">
var canvas = document.getElementById('fireworks');
var ctx = canvas.getContext('2d');
var fireworks = [];
function Firework() {
this.init = function() {
this.x = Math.random() * canvas.width;
this.y = canvas.height;
this.color = '#' + Math.floor(Math.random() * 16777215).toString(16);
this.radius = 2;
this.velocity = {
x: Math.random() * 6 - 3,
y: Math.random() * 3 + 1
};
this.gravity = 0.05;
this.opacity = 1;
this.time = 0;
this.maxTime = Math.random() * 50 + 100;
};
this.draw = function() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
ctx.fillStyle = this.color;
ctx.globalAlpha = this.opacity;
ctx.fill();
};
this.explode = function() {
for (var i = 0; i < 50; i++) {
var particle = new Particle();
particle.x = this.x;
particle.y = this.y;
particle.color = this.color;
var angle = Math.random() * Math.PI * 2;
var speed = Math.random() * 6;
particle.velocity.x = Math.cos(angle) * speed;
particle.velocity.y = Math.sin(angle) * speed;
fireworks.push(particle);
}
};
this.update = function() {
this.draw();
this.x += this.velocity.x;
this.y -= this.velocity.y;
this.velocity.y -= this.gravity;
this.opacity -= 0.01;
this.time ++;
if (this.time >= this.maxTime) {
this.explode();
fireworks.splice(fireworks.indexOf(this), 1);
}
};
}
function Particle() {
this.x = 0;
this.y = 0;
this.color = '#FFF';
this.radius = 2;
this.velocity = {
x: 0,
y: 0
};
this.gravity = 0.05;
this.opacity = 1;
this.draw = function() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
ctx.fillStyle = this.color;
ctx.globalAlpha = this.opacity;
ctx.fill();
};
this.update = function() {
this.draw();
this.x += this.velocity.x;
this.y += this.velocity.y;
this.velocity.y += this.gravity;
this.opacity -= 0.03;
};
}
function animate() {
requestAnimationFrame(animate);
ctx.clearRect(0, 0, canvas.width, canvas.height);
if (Math.random() < 0.03) {
var firework = new Firework();
firework.init();
fireworks.push(firework);
}
for (var i = 0; i < fireworks.length; i++) {
fireworks[i].update();
}
for (var i = 0; i < fireworks.length; i++) {
if (fireworks[i].opacity <= 0) {
fireworks.splice(i, 1);
}
}
}
animate();
</script>
</body>
</html>
```
这个例子中,我们首先创建了一个Canvas元素,并且定义了一些CSS样式来设置它的背景色和居中。我们使用了JavaScript来实现烟花效果,通过创建Firework和Particle类来表示烟花和烟花粒子,然后使用Canvas上下文中的方法来绘制它们。
在animate函数中,我们使用requestAnimationFrame方法来循环调用该函数,不断更新Canvas中的状态。每隔一定的时间间隔,我们创建一个新的烟花对象并将其加入到fireworks数组中。然后,我们遍历该数组,更新每个烟花和烟花粒子的状态,并将它们绘制到Canvas中。最后,我们从数组中删除已经不可见的烟花和烟花粒子,以免占用过多的内存。